Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make AJAX "get" function synchronous / how to get the result?

I'm experiencing a problem of $.get function. The url contains JSON

my code:

 xyz = null

    $.get('http://www.someurl.com/123=json', function(data) {
       var xyz = data.positions[0].latitude;
    });

alert(xyz);
//some more code using xyz variable

I know that xyz will alert a null result because the $.get is asynchronous.

So is there any way I can use the xyz outside this get function?

like image 802
Diolor Avatar asked Jun 10 '12 22:06

Diolor


People also ask

How do you make AJAX request synchronous?

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. So in your request, you must do async: false instead of async: "false" .

Can AJAX requests be made synchronous?

AJAX can access the server both synchronously and asynchronously: Synchronously, in which the script stops and waits for the server to send back a reply before continuing. Asynchronously, in which the script allows the page to continue to be processed and handles the reply if and when it arrives.

How do I return AJAX result?

Hello @kartik, What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, onComplete): somefunction: function(callback){ var result = ""; myAjax = new Ajax.

Is AJAX synchronous or asynchronous?

Ajax requests are Asynchronous by nature, but it can be set to Synchronous , thus, having the codes before it, execute first.


1 Answers

get is a shortcut. You can do the same, but synchronous, using:

var xyz = null


$.ajax({ url: 'http://www.someurl.com/123=json', 
         async: false,
         dataType: 'json',
         success: function(data) {
              xyz = data.positions[0].latitude;
            }
        });


alert(xyz);

You'll have to declare the xyz variable before the ajax call, though.

like image 59
moribvndvs Avatar answered Oct 11 '22 19:10

moribvndvs