How to return data from ajax success function?

In my JavaScript starter app, I make an ajax request to retrieve data from the server. As soon as I receive the data, I want to return this piece of information to the view.

var view_data; $.ajax({ url:"/getDataFromServer.json", //async: false, type: "POST", dataType: "json", success:function(response_data_json) { view_data = response_data_json.view_data; console.log(view_data); //Shows the correct piece of information return view_data; // Does not work. Returns empty data } }); // return view_data; --> Keeping the return outside of the ajax call works but then I need to make my ajax call synchronous in order for this return clause to be executed after the ajax call fetches data. 

How can I do it?

+7
javascript jquery ajax
source share
2 answers

Instead of returning data from success : pass data to the function.

 var view_data; $.ajax({ url:"/getDataFromServer.json", //async: false, type: "POST", dataType: "json", success:function(response_data_json) { view_data = response_data_json.view_data; console.log(view_data); //Shows the correct piece of information doWork(view_data); // Pass data to a function } }); function doWork(data) { //perform work here } 
+12
source share

ajax by nature asyc. The code does not wait for a response from your success callback, so the data is not accessible outside of success unless it is passed.

You will need to process the data inside success, try calling a separate method / function:

 function handleResponse(data) { // do something with data } success:function(response_data_json) { handleResponse(response_data_json.view_data); } 

here are the docs on jquery ajax method

You can also use an external success function, rather than the annon built-in string, which calls the function anyway. it will still pass data as a parameter

 function handleResponse(data) { // do something } $.ajax({ url:"/getDataFromServer.json", //async: false, type: "GET", dataType: "json", success:handleResponse }); 

UPDATE: as pointed out in the comments, you might be better off using an http get request rather than a post . they have advantages , but get requests can be cached, so for data retrieval this can lead to better performance.

+2
source share

All Articles