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?
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" .
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.
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.
Ajax requests are Asynchronous by nature, but it can be set to Synchronous , thus, having the codes before it, execute first.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With