How/Whether to rewrite async:false AJAX function? - javascript

I'm using an AJAX call with async:false to return data, like this:
var my_data = my_function(10, 20);
function my_function(value1, value2) {
var returnData;
$.ajax({
type: 'POST',
url: 'my_function.php',
data: { variable1: value1, variable2: value2 },
success: function(data) { returnData = data; },
async:false
});
return returnData;
};
Notice that I've set async:false, which is necessary in the context of my code, and works perfectly.
Howverer, at the JQuery API, this message is provided for the entry on async:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is
deprecated; you must use the success/error/complete callback options
instead of the corresponding methods of the jqXHR object such as
jqXHR.done() or the deprecated jqXHR.success().
I'm having trouble making sense of that warning as regards my function, as I'm not using $.Deferred in my routine; the warning still may apply in a way I don't appreciate. So, is it safe to leave the code as-is, or should it be rewritten in light of the deprecation of async, and if so, how should it be rewritten? (I need the function performed synchronously.)
Many thanks!

The code you provided looks good. The following is a version that is being deprecated (don't do this):
var my_data = my_function(10, 20);
function my_function(value1, value2) {
var returnData;
$.ajax({
type: 'POST',
url: 'my_function.php',
data: { variable1: value1, variable2: value2 },
async:false
}).success(function(data) { returnData = data; });
return returnData;
};

Related

What's a non-deprecated way of doing a synchronous ajax call using jQuery?

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
});

jsfiddle jquery ajax not returning data as expected

I'm trying to a jquery ajax call on jsfiddle but am having an issue:
var ajax1 = function () {
return $.ajax({
type: "post",
url: "/echo/json/",
data: {
name: "thomas!"
},
dataType: 'json'
});
};
var res = ajax1();
console.log(res);
prints an entire deferred object to the console. It includes responseText which I thought perhaps is what I should try to access, but I get undefined.
console.log(res.responseText);
I tried this once before with HTML and everything seemed to work, but the JSON is failing for some reason.
ajax returns a promise object, not the result of the ajax request. You need to register a success callback to get the value returned by the ajax request
It should be
var ajax1 = function () {
return $.ajax({
type: "post",
url: "/echo/json/",
//also the format for json request is as follows
data: {
json: JSON.stringify({
name: "thomas!"
})
},
dataType: 'json'
});
};
var res = ajax1();
res.done(function (data) {
console.log(data)
})
Demo: Fiddle
You are correct, JQuery returns a Deferred object instance.
You should therefore be calling done() on the object to get the data:
var res = ajax1();
res.done(function(data) { console.log(data); });
$.ajax() returns a jqHXR instance (which implements the Deferred pattern). When you return this from the function you are returning the jqHXR object. This implements a done() method which is passed a callback function.

Accessing variable from callback using AJAX in jQuery

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);

ajax call doesnt return the data from external JS file

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.

Using a non-anonymous callback function for jQuery AJAX

I would to use a callback function in the same 'class' when the ajax request is successful. Here's the code
$.ajax({
type: 'get',
url: ajax_url,
success: this.callback
})
this.callback = function() {
// ERROR! this doesn't point to the right context!
this.run_some_process();
}
Are there any built-in JavaScript constructs that can allow me to get or save the correct context, without having to resort to a custom delegate function?
If I understand your question correctly.
var that = this;
$.ajax({
type: 'get',
url: ajax_url,
success: that.callback
})
that.callback = function() {
// ERROR! this doesn't point to the right context!
that.run_some_process();
}
Have a look at $.ajax's 'context' option.

Categories

Resources