Tiny
Tiny

Reputation: 27899

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?

Upvotes: 2

Views: 8457

Answers (4)

jbabey
jbabey

Reputation: 46647

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

Upvotes: 4

aknosis
aknosis

Reputation: 4308

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

Upvotes: 4

epascarello
epascarello

Reputation: 207511

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

Upvotes: 4

Steven Hunt
Steven Hunt

Reputation: 2321

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.

Upvotes: 11

Related Questions