0

I am using the ajax to fetch data from server.

function getData(){
     $.ajax({
           ......,
           success: function(resp){
               console.log(resp);
               return resp;
           }

    });
}

But when I try

var fetchedData = getData();

Then fetchData is empty.

But when I checked console then there is data.

Can anyone help me?

user3305818
  • 184
  • 3
  • 15
  • 2
    Please read http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Reinstate Monica Cellio Apr 29 '14 at 08:47
  • first check you got any response for your request – Mr.G Apr 29 '14 at 08:50
  • to check for response, if you're using firebug or chrome development tools, just right click your console window and choose Log XMLHTTPresults. You will see if your page returns a result – Jereme Apr 29 '14 at 08:51
  • @Mr.G He's using the success callback. His problem is that he's trying to run asynchronous code in a synchronous manner, hence my comment above, with a link that explains this. – Reinstate Monica Cellio Apr 29 '14 at 08:52
  • I think you should use synchronous request although its very bad idea!!! – Just code Apr 29 '14 at 09:00
  • I have checked the link provide by the **Archer** this is answer to my question. Thanks **Archer** – user3305818 Apr 29 '14 at 09:00
  • 1
    Please check the auto suggestions comes while posting the question. You may get any one question which is similar with your question and may it solve your problem. –  Apr 29 '14 at 09:05

1 Answers1

0

You should use a callback function.

function getData(callback){

     $.ajax({
           ......,
           success: function(resp){
               callback(resp);
           }

    });


}

function getResult(data)
{
 console.log(data);

}

To call this-

getData(getResult);

Edit- Also a better answer is available here-How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Ashutosh
  • 1,000
  • 15
  • 39