I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});
Related
I have gone through many topics on stack overflow for jquery asynchronous AJAX requests. Here is my code.
funciton ajaxCall(path, method, params, obj, alerter) {
var resp = '';
$.ajax({
url: path,
type: method,
data: params,
async: false,
beforeSend: function() {
$('.black_overlay').show();
},
success: function(data){
console.log(data);
resp = callbackFunction(data, obj);
if(alerter==0){
if(obj==null) {
resp=data;
} else {
obj.innerHTML=data;
}
} else {
alert(data);
}
},
error : function(error) {
console.log(error);
},
complete: function() {
removeOverlay();
},
dataType: "html"
});
return resp;
}
The problem is, when I use asyn is false, then I get the proper value of resp. But beforeSend doesn't work.
In case, I put async is true, then its beforeSend works properly, but the resp value will not return properly, Its always blank.
Is there any way to solve both problems? I would get beforeSend function and resp value both.
Thanks
Use async:false and run the function you assigned to beforeSend manually before the $.ajax call:
var resp = '';
$('.black_overlay').show();
$.ajax({
...
Either that or learn how to use callback functions with asynchronous tasks. There are many nice tutorials on the web.
Take the resp variable out from the function
Create one extra function respHasChanged()
when you get the data successfully, use the code
resp = data;respHasChanged();
You can restructure on this way, (why no use it in async way?)
function ajaxCall(path, method, params) {
return $.ajax({
url: path,
type: method,
data: params,
beforeSend: function() {
$('.black_overlay').show();
},
dataType: "html"
});
}
Call in your javascript file
ajaxCall(YOUR_PATH, YOUR_METHOD, YOUR_PARAMS)
.done(function(data) {
console.log(data);
// DO WHAT YOU WANT TO DO
if (alerter == 0 && obj !== null) {
obj.innerHTML = data;
} else {
alert(data);
}
}).fail(function(error) {
console.log(error);
}).always(function() {
removeOverlay();
});
I have trouble async disable ajax. I have the following code:
function GetDataFromUninorte() {
link="http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.csv/0e3c22b1-0ec4-490d-86a2-d4bc4f512030";
var result=
$.ajax({
url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
type: 'GET',
async: false,
dataType: 'json',
success: function(response) {
console.log("Inside: " + response);
}
}).responseText;
console.log("Outside: "+result);
return result;
}
And I get the following result:
"Outside" always runs first
As you can see, "Outside" always runs first and the result is undefined and can not process data.
I have already tried
When ... Then
Async = false
passing data as parameters I / O function
and other things, but nothing
:/
... Beforehand thank you very much
(I am not a native english speaker, I apologize if I do not write well)
[Solved]
Maybe is not the best form, but in the "success:" statement I call a function that receive the ajax response and trigger the rest of the process, in this way I not need store the in a variable and the asynchrony not affect me.
Use can use callbacks, you can read more here
function GetDataFromUninorte(successCallback, errorCallback) {
link="http://www.uninorte.edu.co/documents/...";
$.ajax({
url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
type: 'GET',
async: false,
dataType: 'json',
success: successCallback,
error: errorCallback
});
}
function mySuccessCallback(successResponse) {
console.log('callback:success', successResponse);
}
function myErrorCallback(successResponse) {
console.log('callback:success', successResponse);
}
GetDataFromUninorte(mySuccessCallback, myErrorCallback);
Or you can use promises (bad support in IE browsers)
function GetDataFromUninorte() {
return new Promise(function(resolve, reject) {
link="http://www.uninorte.edu.co/documents/...";
$.ajax({
url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
type: 'GET',
async: false,
dataType: 'json',
success: resolve,
error: reject
});
});
}
GetDataFromUninorte()
.then(function(successResponse){
console.log('promise:success', successResponse);
}, function(errorResponse){
console.log('promise:error', errorResponse);
});
AJAX being asynchronous by nature, you need to pass callback, which will be called when the ajax response is received. You may then access responseText from the xhr object.
You can also you jQuery Deferred and promise to get around your problem like below:
function GetDataFromUninorte() {
var defObject = $.Deferred(); // create a deferred object.
link="http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.csv/0e3c22b1-0ec4-490d-86a2-d4bc4f512030";
$.ajax({
url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
type: 'GET',
async: false,
dataType: 'json',
success: function(response) {
console.log("Inside: " + response);
defObject.resolve(response); //resolve promise and pass the response.
}
});
return defObject.promise(); // object returns promise immediately.
}
and then:
var result = GetDataFromUninorte();
$.when(result).done(function(response){
// access responseText here...
console.log(response.responseText);
});
You should avoid making AJAX synchronous by setting async:false as that will block further interactions on the User Interface.
Use this:
function GetDataFromUninorte() {
link="http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.csv/0e3c22b1-0ec4-490d-86a2-d4bc4f512030";
var result=
$.ajax({
url: 'http://whateverorigin.org/get?url=' + link +"&callback=?" ,
type: 'GET',
**timeout: 2000,**
async: false,
dataType: 'json',
success: function(response) {
console.log("Inside: " + response);
}
}).responseText;
console.log("Outside: "+result);
return result;
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am new to AJAX and I need to find a way to return an AJAX JSON response back to the calling function. Is there any way to achieve this.
My code snippet:
function requestAjaxWebService(webServiceName, method, jsonData) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
return returnData;
}
jQuery.ajax() performs asynchronous HTTP request. Hence, you can't return its response synchronously (which your code is trying to do).
If the request succeeds, the success(data, textStatus, jqXHR) handler will get called at some point (you don't know when).
Here is one way you could modify your code:
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data, textStatus, jqXHR) {
callback(true, data); // some method that knows what to do with the data
},
error: function(jqXHR, textStatus, errorThrown){
callback(false, errorThrown);
}
});
}
callback should be a reference to a method like:
function onData(isSuccess, dataOrError)
{
if (isSuccess) {
// do something with data
} else {
console.error(dataOrError);
}
}
Update If the settings object is needed in the callback for some reason:
function onData(isSuccess, settings, jqXHR, errorThrown)
{
if (isSuccess) {
// do something with the data:
// jqXHR.responseText or jqXHR.responseXML
} else {
// do something with error data:
// errorThrown, jqXHR.status, jqXHR.statusText, jqXHR.statusCode()
}
}
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
var settings = {
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
};
settings.success = function(data, textStatus, jqXHR){
callback(true, settings, jqXHR);
};
settings.error = function(jqXHR, textStatus, errorThrown){
callback(false, settings, jqXHR, errorThrown);
};
$.ajax(settings);
}
requestAjaxWebService("name", "POST", "json", onData);
You can also use .done() and .fail() callbacks of jqxhr object instead of callbacks in settings object, as obiTheOne's answer suggests. It may look neater, but is not actually important here.
jQuery.ajax is an asynchronous function, so normally it doesn't return anything.
You can anyway return a value to the original function by setting the async option to false, but is not recommended, because a synchronous request will block the rest execution of the rest of your code until a response will be returned.
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
async: false,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
}
take a look at this example: jsbin sync ajax example
You should instead use a callback (the standard way) to handle the response
function onSuccess (data) {
console.log(data);
}
function onFail (error) {
console.log('something went wrong');
}
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: onSuccess,
error: onError
});
}
Or you can return a Promise (a sort of async object) that will change value as soon as the request will be fullfilled
function requestPromise (webServiceName, method) {
return $.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
});
}
requestPromise('...', 'GET').done(function (data) {
console.log(data);
});
refs:
jquery.ajax params
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Synchronous calls with jquery
I am trying to return a value from a function that contains an ajax call (please see code below).
The returnValue variable is undefined at the alert and when it returns. Can anyone help please?
function getLightboxImages(){
var returnValue;
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
async: false,
dataType: "jsonp",
success: function (result) {
returnValue = result
}
});
alert(returnValue);
return returnValue;
}
The alert would have to be placed in the success function, as that is called when ajax returns. What you have above will send the request and then try to alert the returned value before the request is completed.
try this code, for JSONP you have to use callback function rather than success method.
$.ajax({
url: 'http://test.domain.com/WebService.svc/GetAllI',
type: 'GET',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpCallbackfunction",
error: function () {
alert("Error in Jsonp");
}
});
function jsonpCallbackfunction(responseData) {
alert(responseData);
}
http://cmsnsoftware.blogspot.com/2012/02/how-to-use-cross-domain-ajax-request.html#0
function getLightboxImages(){
var returnValue;
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
async: false,
dataType: "jsonp",
success: function (result) {
returnValue = result
}
});
alert(JSON.stringify(returnValue));
return returnValue;
}
Cross-domain requests can only be async, as cross-domain requests rely on a dynamic script tag, which can never be synchronous and must use datatype json and the GET method.
For same domain requests, try stringifying json objects before alerting, like above!
You can't make synchronous JSONP requests.
Use a callback instead of return:
function getLightboxImages(callback) {
jQuery.ajax({
url: "http://test.domain.com/WebService.svc/GetAllI",
data: { id: "2", hash:"MaD01" },
dataType: "jsonp",
success: function (result) {
callback(result);
}
});
}
Usage:
getLightboxImages(function(result){
alert(result);
});
I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).
a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
return response;
});
}
What's happening, however, is that the append function is running before "a" has been defined in the getAjax function. Any thoughts?
AJAX is asynchronous. This means that the code in the success handler is delayed until the request is successful, while the rest of the code continues as normal. You need to put the relevant code in the AJAX success handler:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
$(document.body).append('<div>'+response+'</div>');
});
}
Note that I have also optimised your body selector by using the native Javascript document.body rather than using the standard tag selector.
Edit Callback version
function getAjax(callback) {
$.ajax({
type: 'GET',
url: 'someURL',
success: callback
});
}
You can now do the code inline using a callback function:
getAjax(function(response) {
$(document.body).append('<div>'+response+'</div>');
});
or
getAjax(function(response) {
alert(response);
});
or whatever.
The code inside the anonymous function call will be processed when the AJAX request is complete.
There are two ways to taggle this. one is to use the success callback:
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
the other is to set async to false http://api.jquery.com/jQuery.ajax/:
var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
async: false,
success: function(response) {
a = response;
});
}
Important note on non async:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
Why don't you return the response to another function in the success callback. This should handle your need for different responses:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
}
function AppendResponse(response) {
$('body').append('<div>'+response+'</div>');
}
One suggestion I have is to pass a trigger to the command you want to run into the AJAX function so that it will run after AJAX has received a response-
a = getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
inputText(response);
});
}
inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}
That way you can create if statements / other alternatives to continue to use the same AJAX command for different results
You can give a handler to the function getAjax(), but if the user needs the information for the next decision then why not wait using async: false?
function getAjax(handler) {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
handler(response);
});
};
function callGetAjax(response) {
if(response === undefined) {
getAjax(callGetAjax);
} else {
$('body').append('<div>'+response+'</div>');
}
}