-2

I'm trying to simply get a response from a jQuery $.get() call, and store it to a variable. It's proving to be much more difficult than I would have thought. Here is my code:

var response;
    $.get(("action.php?action=addFolder&folderName=" + input),  
        function(data, status){
             response = data
        }
    );
return response;

But response is always undefined or null. How can I fix this?

yathern
  • 319
  • 1
  • 3
  • 14

1 Answers1

5

This is because ajax is async. This means the ajaxcall is still doing its thing, and you are allready returning 'response'.

If you need 'response' for something (which I kinda asume), do something with it in the oncomplete of the ajaxcall. The function you use in the get is the function that gets trigger oncomplete.

To clarify async a bit more for those who dont know what I mean*:

You create the variable 'response'. After that the ajax gets started. After that you return it. The important thing in that list, is that it gets returned after the ajax STARTS. If the ajax would take 5 seconds, the variable will have it's value after 5 seconds.

*this is simplefied

Martijn
  • 15,791
  • 4
  • 36
  • 68