When you are calling $.post()
, which is really just a wrapper for $.ajax()
, you are doing two things: 1, initiating an asynchronous request to the server, and 2, setting up an event handler for when the request is completed (i.e. when the response is received).
This event handler works in much the same way as any other event handler, such as those setup using $.click()
or $.keyDown()
. So, the $.post()
call completes almost instantly and the code after it continues to execute. Then, some time later, the response is received and the callback (function you pass in to $.post()
) will be fired.
So what you need is something more like:
$.post('myphpcode.php', {myJSData}, function(data) {
// this is executed only when the request is complete.
// the data parameter is the result of the call to the backend.
});
// code here is executed immediately after the request is fired off
P.S. you generally use "post" requests for sending data to the server; if you are only retrieving data, it is more common to use a "get" request, i.e. $.get()
instead of $.post()
.