Code explains all:
//
// … code ...
//
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
var my_data = data;
}
});
//
// … code ...
//
console.log(my_data); // NOT in scope
How do I get access to my_data outside of the AJAX call? I've read that maybe a closure is needed? I can't find any examples that do want I want though.
Many thanks.
Ajax is async call and success may be fired after console.log, you can call a function from success and pass data to it.
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
yourFun(data);
}
});
function yourFun(data)
{
}
To giving function instead of success.
$.ajax({
dataType: "json",
url: "foo",
success: yourFun
});
function yourFun(data)
{
}
Generally speaking, you don't. AJAX calls are asynchronous so there's no guarantee of a value immediately after the jQuery.ajax() function has executed; you need to wait until the AJAX call has completed, and the success callback has executed, before you attempt to use that variable.
The easiest approach is to just use that value inside the success callback. If you really need it to be available outside then make it a variable that's visible to all of your code (not necessarily global, depending on how your code is structured), and check that it has a value before you attempt to use it in any other functions.
Define my_data as global as below,
var my_data;
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
//
// … code ...
//
console.log(my_data); // NOT in scope
Declare my_data variable globally..
var my_data = data;
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
Use my_data as gloabl variable to access data outside of ajax.
var my_data = '';
$.ajax({
dataType: "json",
url: "foo",
success: function(data) {
my_data = data;
}
});
console.log(my_data);
Related
I have a specific requirement with nested ajax calls. I am trying to set a globally accessible variable inside success of one ajax call and this ajax call is being invoked inside success of another ajax call. Eventually the parent success method of parent ajax call utilizes the global variable to perform further operations. The problem is that the value of global variable always remains blank. It works if I make the second ajax request as async:false; but this solution defeats the very purpose of using ajax in the first place.
Let me share a small sample code to illustrate my problem:
//global variables
var xURL = "https://sampleurl.com";
var glblID = "";
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json",
success: function (msg) {
//some js code here
//second ajax call
FetchID();
//more js code here
if(glblID != "")
{
window.location.href = xURL + "?id=" + glblID
}
else
{
window.location.href = xURL;
}
}
});
function FetchID()
{
$.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json",
success: function (data) {
glblID = data.d;
}
});
}
As of jQuery 1.5 implement the Promise interface, giving them all
the properties, methods, and behavior of a Promise
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json"
}).then(function (msg) {
//second ajax call
FetchID().then((data) => {
var glblID = data.d;
if (glblID != "") {
//do something with glblID
} else {
//do something else
}
});
});
function FetchID() {
return $.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json"
});
}
I've got a small javascript function that's only purpose is to call a script to get some data from the database so it can be used by other functions on the client side.
I'm using a jQuery call to get the data but for me to pass the object out of the success functions scope I need to turn asynchronous off which raises a deprecation warning.
My function works as intended currently but I'd like to use a method that isn't deprecated. Here is my function:
function getData(ID) {
var Data = {};
$.ajax({
url: 'script',
method: 'POST',
dataType: 'json',
async: false,
data: {action: 'get', id: ID },
success: function(response) {
Data = response;
})
});
return Data;
}
I've changed the variable names for privacy reasons so apologies if they're vague.
Also why is synchronous calls considered harmful to the end users experience?
As AJAX call is asynchronous, you will always get blank object ({}) in response.
There are 2 approach.
You can do async:false
To get response returned in AJAX call try like below code. Which wait for response from server.
function getData(ID) {
return $.ajax({
url: 'script',
method: 'POST',
dataType: 'json',
//async: true, //default async call
data: {action: 'get', id: ID },
success: function(response) {
//Data = response;
})
});
}
$.when(getData(YOUR_ID)).done(function(response){
//access response data here
});
Why the final console log is undefined?Variable time has a global scope and ajax call is async.
This is my code:
var time;
$.ajax({
async:"false",
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function(data) {
console.log(data);
time=data;
},
error: function(data) {
console.log("ko");
}
});
console.log(time);
Change async to the boolean false.
http://api.jquery.com/jQuery.ajax/
var time;
$.ajax({
async: false,
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
console.log(data);
time = data;
},
error: function (data) {
console.log("ko");
}
});
console.log(time);
Also, note that if you need to use dataType: 'jsonp' here for cross-domain, you won't be able to synchronize -- so use a promise.
var time;
$.ajax({
dataType: 'jsonp',
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
time = data;
},
error: function (data) {
console.log("ko");
}
})
.then(function(){ // use a promise to make sure we synchronize off the jsonp
console.log(time);
});
See an example like this here using Q.js:
DEMO
In your code, you initialize the global variable 'time' as 'data'. Where does this data variable come from? If the data variable is not global also, when you try to use console.log(time); , it may be undefined because the data variable is undefined.
Make sure both variables are within scope to be used globally. That might work. Good luck!
OK, a bit contrived, but I hope it shows the point regarding scope of time and timing ...
$.ajax({
async: false,
dataType: 'jsonp',
type: 'GET',
url: "http://www.timeapi.org/utc/now.json",
success: function (data) {
console.log(data.dateString);
time = data.dateString;
},
error: function (data) {
console.log("ko");
}
});
window.setTimeout("console.log('time: '+time)",3000);
JSfiddle
I'm making ajax POST request from javascript function:
function UpdateMetrics() {
$.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
...
}
});
}
From my handler, I'm sending json string with:
context.Response.write(json);
I think I'll get it in msg.
I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:
context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count));
If this is right way to do it, how can I access it in my success function?
To access headers in your success function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.
So, your function should look like:
success: function (msg, status, jqXHR) {
var jsonUpdatedData = msg;
...
}
However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.
You also need to tell jQuery to interpret the response as json by setting
dataType: "json"
Otherwise, it will just be returned to you as text.
Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.
function UpdateMetrics() {
var callback = $.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
var headerdata = callback.getResponseHeader("MaxCount");
// Where MaxCount is name provided in the header.
...
}
});
}
Thanks
I am trying to implement Repository pattern in JavaScript. I have ViewModel which i want to initialize with the data when i call Initialize method on it. Everything seems to be falling in places except that i am not able to return the data from my AJAX call. I can see that data is coming back from the ajax call but when i trying to capture the data in SomeViewModel's done function, it is null.
Can someone please point me out where i am going wrong here?
P.S: Please notice that i am not making Async call so the call chain is properly maintained.
This is how my Repository looks like:
function SomeRepository(){
this.LoadSomeData = function loadData()
{
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
return data;
},
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
}
};
This is how my ViewModel looks like:
function SomeViewModel(repository){
var self = this;
var def = $.Deferred();
this.initialize = function () {
var def = $.Deferred();
$.when(repository.LoadSomeData())
.done(function (data) {
def.resolve();
});
return def;
};
}
This is how i am calling from an aspx page:
var viewModel = new SomeViewModel(new SomeRepository());
viewModel.initialize().done(alert('viewmodel initialized'));
alert(viewModel.someProperty);
I have used successfully an auxiliar variable to put the ajax result, when ajax call is inside a function (only works if ajax is async=false) and i need the function does return the ajax result. I don't know if this is the best solution.
function ajaxFunction(){
var result='';
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
result=data;
},
error: ajaxFailed
});
return result;
}
Doesn't matter that it's synchronous (though it really shouldn't be). Returning a value from inside the ajax callback will not cause the value to be returned from the containing function.
Using asynchronous ajax is generally a much better idea anyway, but that will force you to create an API that allows its clients to pass in handlers to be called when the ajax request completes. To do that, you'd give your "LoadSomeData" function a parameter. A caller would pass in a function, and your ajax "success" handler would pass on the results (or some transformation of the results; depends on what it is that you're doing) to that callback. It's the same idea as the callbacks used in the ajax call itself.