-4

Possible Duplicate:
return AJAX callback return

I have made a JQuery code using AJAX, but despite all my efforts (trying $.post, $.get and $.ajax) I am not able to get any response nor using it in my code. Example code:

var r = $.post("ajaxpage.php", function(data) {return data});
console.log(r); // nothing
Community
  • 1
  • 1
Cranio
  • 9,647
  • 4
  • 35
  • 55
  • Huh? So you asked a question only to immediately paste an answer to it? – CAbbott Jun 21 '12 at 21:13
  • @CAbbott Yes sir, that's precisely what I have done. – Cranio Jun 21 '12 at 21:14
  • This is not a very specific question, and no one else could have answered it even if they'd been given the chance. Furthermore, it's one that's been asked and answered MANY many times on SO in the past. If you're going to answer your own questions, please make it something that actually adds to the general body of knowledge. – Blazemonger Jun 21 '12 at 21:16
  • @Cranio Why did you put up this question and answer it immediately? – Styxxy Jun 21 '12 at 21:17
  • @Blazemonger It may be not specific, but I have answered FOUR times question like these in the past two days, I thought that it was a common problem and that sharing some insights about how ajax works would be really useful. – Cranio Jun 21 '12 at 21:17
  • @Styxxy Self-answering is encouraged to share relevant information. – Cranio Jun 21 '12 at 21:18
  • 3
    @Cranio So instead of linking askers to one of those four questions, you decided to muddy the water further by contributing a fifth? – Blazemonger Jun 21 '12 at 21:18
  • @Cranio Yes it is, I know. But this is just not how it works. Just answer it somewhere very well, and link it to the other questions or mark those questions as duplicate. No need to put it here a 5th time... – Styxxy Jun 21 '12 at 21:19
  • @Blazemonger So instead of a short, on the fly answer like the ones I found or gave, I decided to *take the time* and effort to write a more lenghty post, with a real-life analogy. I'm VERY surprised it bothers you. – Cranio Jun 21 '12 at 21:19
  • 1
    Then answer it somewhere else this lengthy, or edit your older posts, or, whatever. Really no need to put this question up. It bothers me as much as it bothers @Blazemonger. – Styxxy Jun 21 '12 at 21:21
  • what bother people is you are "asking" a question, a poorly written one at that, and then answering it like you authority on that matter. Put this in a blog post, it doesn't belong here like this. – Eonasdan Jun 21 '12 at 21:21
  • 1
    Then just amplify one of your existing answers. Whether it's [officially endorsed](http://blog.stackoverflow.com/2012/05/encyclopedia-stack-exchange/) or not, the practice of posting badly-written questions just so you can be the only one who answers is a poor habit to get into. – Blazemonger Jun 21 '12 at 21:21
  • I have not linked the answers to that questions because I think they were not satisfactory for a beginner programmer. I'm open to be criticized on this answer, that's the way it should be; but it comes to me as a surprise that an effort to organize the info and explain it in a clear way must be shunned. – Cranio Jun 21 '12 at 21:21
  • 4
    @Cranio - I think you're kinda missing the point of SO. If you have an answer to a question then post it at the question. Self-answering is for if you have found a solution to your own question. SO isn't a programming blog site. – CAbbott Jun 21 '12 at 21:22
  • BTW: the "badly written" question is the exact form in which i have **found** these questions. I think it's normal for beginners to put up a code and a "bad question" like the one I wrote. So, math done, do you think I should eliminate this post? I'm very willing to cooperate, I just thought it was useful. – Cranio Jun 21 '12 at 21:23
  • 2
    Speaking only for myself, I would prefer you (a) amplify one of your existing answers and (b) link to it often in the future. This is a well-established practice on SO, and one I think is better than "blogging" a new question. – Blazemonger Jun 21 '12 at 21:24
  • 1
    The answer is good, but you should put them as answer on the other questions and maybe "save" it or put it somewhere up on a blog. If you come across this same question, you can link or copy this question (with maybe some specific modification to the actual question). – Styxxy Jun 21 '12 at 21:24
  • http://blog.stackoverflow.com/2012/05/encyclopedia-stack-exchange/ -- I know answering-your-own-question is official policy now. I just happen to disagree with it in most cases. – Blazemonger Jun 21 '12 at 21:26
  • @Blazemonger Sometimes it's difficult to amplify pre-existing answers; but your suggestion it's worth noting, maybe I should be more focused on giving even longer and more meaningful answers to OP's. – Cranio Jun 21 '12 at 21:26
  • @Styxxy: Yeah, I **really** like it put it that way, maybe it's better done like you suggest. – Cranio Jun 21 '12 at 21:26
  • To all: I'm new to SO, so unlike most seasoned members I may miss some important points. I'm sorry that my effort bothered you and I will try to be a considerate member; just bear in mind that my effort was genuine. – Cranio Jun 21 '12 at 21:28
  • 2
    No doubt it was ;). There are plenty of possible ways to share this answer anyway. (Again, the answer itself is quite good, so keep up that kind of quality.) – Styxxy Jun 21 '12 at 21:29
  • @CAbbott as Blazemonger says, there are plenty of *encouraged* examples of self-answering as a divulgative mean, not only if I find the solution. So, you're **wrong**. Maybe I have missed the meaning of "useful" or "good question/answer", Blazemonger made some important points, but as far as self-answers are concerned I'm totally in-policy (yeah, I've actually **read** faqs and the blog). – Cranio Jun 21 '12 at 21:30
  • I would move in the chat for further discussions :) – Cranio Jun 21 '12 at 21:32
  • I don't mind at all that you've posted an encyclopedic self-answered question; from the link Blazemmonger posted, I think there's ample evidence that such fine. I object to the fact that you **knowingly posted a duplicate question**, and I have voted to close it as a duplicate. – apsillers Jun 22 '12 at 00:10
  • @apsillers I would call it "expansion" and not "duplicate", but maybe I missed to fully understand the concept. – Cranio Jun 22 '12 at 05:54

1 Answers1

4

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.

Cranio
  • 9,647
  • 4
  • 35
  • 55
  • to point out something to avoid misconception, `$.post` returns something, a Deferred object, which hosts several methods to deal with "late" results due to async operations, one of which is `.done()`. – Joseph Jun 21 '12 at 21:13