[Solved] $.ajax, $.post or $.get won’t function, cannot use the response [duplicate]


One of the most common misconceptions of beginner programmers about Javascript and AJAX is to treat the AJAX request as a “normal” function, doing variable assignments or expecting to use immediately the AJAX response in their code.

That’s not how it works though; let’s try to understand how a correct implementation works.

AJAX stands for Asynchronous JavaScript and XML.

We will ignore for a while the XML part (which is more about how the request is carried on, via XMLHttpObject), the Javascript bit is quite obvious (it’s the scripting language we use, with or without JQuery), let’s focus on asynchronous.

Think about AJAX this way: it is roughly like sending a work email to a colleague, while you’re at work, and giving some info; and requesting an action to be taken and/or other info in return; no matter if your friend answers immediately or not, you still have to continue your job because the answer could be delayed (your friend may be particularly busy today).
When your friends answers with relevant info, only then you will address the matter and take appropriate actions. If an action is requested, your colleague will carry it on only when he receives your email.

AJAX works in a similar way: from client-side, you make a request to a server-side page, and expect an action (like writing a row in a database) or a response (some data fetched server-side from the page you are calling.

The important bit is that your JavaScript code continues its execution regardless of the completion of the round-trip, as there can be a significant delay when your client (remember that JS runs client-side) makes an AJAX call to the server (slow server, slow connection, and so on).

So you can’t expect to do things like:

var r = $.post("ajaxpage.php", function(data) {return data});

because $.post doesn’t actually “return” a value like a “regular” function, the variable r cannot be valued by $.post

Instead, you should organize your code based on the done event, which is fired after the AJAX call has completed: it guarantees (if there have been no failures, like server-side errors, not found pages, etc.) that we actually have a response to use in your code on success.
With that event we can call a function that receives the response as a parameter and actually uses it.

$.post("ajaxpage.php").done(useMyResponse);
// rest of the code

function useMyResponse(response)
{
    // do fancy things with the response like:
    console.log(response); // works!
    // or maybe
    $("#someElement").html(response);
}

A shorthand for this would be:

$.post("ajaxpage.php",function (response) { 
     // use response
     console.log(response);
});

Edit: i’m not a native English speaker, forgive my mistakes.

1

solved $.ajax, $.post or $.get won’t function, cannot use the response [duplicate]