Return data from jQuery ajax request

I am trying to get a function to execute an ajax request and then return the interpreted JSON as an object. However, for some reason, once this request is executed, data is only available from within the function.

function getCacheImage(direction) { jQuery.ajax({ url: json_request_string, success: function(data) { return data; } }); } 

How can I make this function return data correctly?

Thanks.

+4
source share
3 answers

You need to either use a synchronous ajax request (not typical or recommended), and grab the data into a variable in the outer scope or figure out how to manipulate the data in the callback function. The problem is that the ajax function returns before the end of the ajax call - it is asynchronous.

Synchronous path:

  function getCacheImage(direction) { var capture; jQuery.ajax({ url: json_request_string, aSync: false, success: function(data) { capture = data; } }); return capture; } 

Typically using a callback

  function getCacheImage(direction,callback) { jQuery.ajax({ url: json_request_string, success: function(data) { callback( data ); } }); } getCacheImage('left', function(data) { ...do something with the data... } 
+9
source

You can not. The first letter of the abbreviation AJAX means asynchrony, which means that AJAX requests are sent and control returns immediately to the calling function. What you need to do is work with the data in the callback function.

+3
source

You are returning data to code calling the callback function. This code cannot send data back in time so that it can be returned from the function that started the request.

Whatever you do with the data, you perform a callback function.

0
source

Source: https://habr.com/ru/post/1299836/


All Articles