1

Apologies if this has been answered elsewhere but I'm pretty new and not sure of search terms that will help me.

I have a form that has this:

<form onsubmit="InsertAppointment()" method="get">

Which calls the following Javascript

    function InsertAppointment()    
{
    alert("moo");
    $.get("test.php", 
        function(data)
            {
                alert(data);
            } 
        );

}

test.php just does

<?php 
 echo "test complete"; 
?>

I was expecting the javascript to return two message boxes one of which says moo, the other test complete, i get the first one but not the latter. I'm really not sure what I'm doing wrong.

1 Answer 1

2

Ajax, which is what the $.get method is (it performs an ajax call) is asynchronous, therefore the form is submitted, and the callback function (the one that alerts data) isn't executed.

Just add a return false; statement right after the $.get(); call, and you'll get the second alert, too. It'll just take that split second longer to pop up (the request has to be sent to the server, the response has to be sent back, and processed, then the response will be alerted). If you don't return false, the submit event will complete and the client will be redirected

Sign up to request clarification or add additional context in comments.

2 Comments

Ok so what i want to do is press the button, have the javascript send through some variables to test.php and depending on the results of test.php either clear the form or not
@user1498194: at the very end of the InsertAppointment function, you'll want to add a return false statement, like I said: in jQuery, that cancels the submit event. To be absolutely safe, you could also change the onsubmit="InsertAppointment()" to onsubmit="return InsertAppointment()". Lastly, to be in tune with conventions: don't use an upper-case as first char for a regular function, that's for constructor functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.