最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ajax call doesn't work when a submit button is used - Stack Overflow

programmeradmin2浏览0评论

I'm trying fetch a live currency rate using the following API.

""

When I click on a button, it alerts the rate and works just fine. I'm using the following Ajax code.

<script type="text/javascript" language="javascript">
    function testCurrencyRate()
    {
        $.ajax({
                datatype:"html",
                type: "GET",
                url: "ajax/LiveCurrencyRate.php",
                data: "t="+new Date().getTime(),
                success: function(response)
                {       
                    alert(response);                    
                },
                error: function(e)
                {
                    alert('Error while fetchig the live currency rate.');                       
                }
            }); 
    }
</script>

The Ajax request goes to the LiveCurrencyRate.php page which is as follows.

$url="";               
$result = file_get_contents($url);
echo $result;   

and the <form></form> which contains the only button which when clicked makes an Ajax request on this URL ajax/LiveCurrencyRate.php.

<form id="testForm" name="testForm" action="" method="post">    
    <input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test" onclick="testCurrencyRate();"/>
</form>

Everything is fine. The problem however arises when I change the button type from type="button" to type="submit", it doesn't work. The alert box in the error part of the Ajax function shows the alert box just for a while and all of a sudden it disappears. I can't find any reasonable cause that may prevent this request from being completed. The same thing worked for me in my previous project but I was using XMLHttpRequest for making Ajax requests. What's going wrong here?

I'm trying fetch a live currency rate using the following API.

"http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj"

When I click on a button, it alerts the rate and works just fine. I'm using the following Ajax code.

<script type="text/javascript" language="javascript">
    function testCurrencyRate()
    {
        $.ajax({
                datatype:"html",
                type: "GET",
                url: "ajax/LiveCurrencyRate.php",
                data: "t="+new Date().getTime(),
                success: function(response)
                {       
                    alert(response);                    
                },
                error: function(e)
                {
                    alert('Error while fetchig the live currency rate.');                       
                }
            }); 
    }
</script>

The Ajax request goes to the LiveCurrencyRate.php page which is as follows.

$url="http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj";               
$result = file_get_contents($url);
echo $result;   

and the <form></form> which contains the only button which when clicked makes an Ajax request on this URL ajax/LiveCurrencyRate.php.

<form id="testForm" name="testForm" action="" method="post">    
    <input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test" onclick="testCurrencyRate();"/>
</form>

Everything is fine. The problem however arises when I change the button type from type="button" to type="submit", it doesn't work. The alert box in the error part of the Ajax function shows the alert box just for a while and all of a sudden it disappears. I can't find any reasonable cause that may prevent this request from being completed. The same thing worked for me in my previous project but I was using XMLHttpRequest for making Ajax requests. What's going wrong here?

Share Improve this question edited Oct 3, 2012 at 18:54 aknosis 4,30824 silver badges35 bronze badges asked Oct 3, 2012 at 18:47 TinyTiny 27.9k112 gold badges351 silver badges604 bronze badges 2
  • Might be because you need to handle it inside the submit action of the form instead of the button click action – wirey00 Commented Oct 3, 2012 at 18:49
  • 1 submit triggers the default behavior of your form Element (including a page reload). It's easy to prevent, there should be tons of questions regarding this already. – m90 Commented Oct 3, 2012 at 18:50
Add a comment  | 

4 Answers 4

Reset to default 11

type="submit" causes the web browser to submit the form via a postback (because your method attribute is set to "POST"), which causes the page to refresh. The action attribute of the <form> tag determines where the data gets sent to, and then that page loads with the data provided. When this happens, all javascript on the page terminates because you are effectively going to a different page or reloading the current one.

The page is submitting because you are not cancelling the default action of the click. You need to stop that event from happening. With your code, you can add a return false to the onclick, but it is better to add the events in an unobtrusive manner.

$("#btnTestCurrencyRate").on("click",function(e){
    testCurrencyRate();
    e.preventDefault();
});

better to catch it on the form submission and not onclick

$("#testForm").on("submit",function(e){
    testCurrencyRate();
    e.preventDefault();
});

When you click the submit button your form is being posted to you web server. You need to prevent the form from posting by using something like:

$("#testForm").submit(function(e){
    e.preventDefault();
});

because your page is submitting. you need to return false from the onclick handler if you want to prevent the submit.

HTML:

<input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test"/>

JS:

document.getElementById('btnTestCurrencyRate').onclick = testCurrencyRate;

function testCurrencyRate() {
    ... snip ...
    return false;
}
发布评论

评论列表(0)

  1. 暂无评论