简体   繁体   中英

ajax call doesn't work when a submit button is used

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM