This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Ajax get data normal, but i dont know how return varname from if statement, with inside loop, with inside function ;).
How can return var username from this statement? Thanks.
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
var username = data.users[i].username;
return username; // !!!How can return this
};
};
}
})
console.log(username) // error: username is not defined
By default, ajax will be executed asynchronously. This means that the result returned has to be handled in the callback:
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
var username = data.users[i].username;
console.log(username);
}
}
}
});
ajax could be executed with the async set to false but this is usually not recommended as it will lock the UI until you get the response from the server.
Ajax is asynchronous.
You should use a callback instead.
var callback = function(username) {
// Do something with username here
console.log(username);
}
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
var username = data.users[i].username;
// call the callback
callback(username);
};
};
}
});
Declare it as a global variable.
var username;
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
username = data.users[i].username;
return username; // !!!How can return this
};
};
}
})
console.log(username);
Or directly send it to a function in ajax success.
Related
So I have a function that executes an ajax call in a for loop. I need to callback another function when the entire for loop is done. Since the ajax calls are running asynchronously, I'm not able to call the next function once the for loop is done.
Here's my code:
for(let i=0; i< industryArray.length; i++){
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
},
error: function (data) {
}
})
}
// Need to call myfunction() here
myfunction() is being called even before the ajax calls are executed. Thanks!
Set ajax asyc state false then it will work
this is a sample example to set ajax asyc false
$.ajax({
url : "/submit/checkuser/",
type : "get",
async: false,
success : function(userStatus) {
if (userStatus == 'Disabled') { // check if user if disabled
} else if (userStatus == 'Deleted') { // check if user if deleted
} else {
};
},
error: function() {
connectionError();
}
});
Right now it wait for the function to get executed and moved to the next line
var pendingRequests=0;
for(let i=0; i< industryArray.length; i++){
if (condition) {
pendingRequests++;
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
pendingRequests--;
if(pendingRequests===0) {
otherFunction()
}
},
error: function (data) {
doSomethingWithError(data)
}
})
}
}
I'm currently working on a project with javascript and jquery.
I'm using a $.ajax call to ask the server for some data. This call is being made within an object I created.
On success, I want to update the data members of such object with the data recieved. It looks something like so:
function Caller() {
this.data1 = 0;
this.data2 = 1;
this.makeRequest = function () {
$.ajax({
url: "some url",
data: somedata,
dataType: "json",
success: function ( data ) {
// update data
}
});
};
};
For passing the original object (Caller) to the succes function, I've tried the following:
function Caller() {
this.data1 = 0;
this.data2 = 1;
this.makeRequest = function () {
var _this = this;
$.ajax({
url: "some url",
data: somedata,
dataType: "json",
success: function ( data ) {
// update data
_this.data1 = data.data1;
_this.data2 = data.data2;
}
});
};
};
Then I tried:
function Caller() {
this.data1 = 0;
this.data2 = 1;
this.makeRequest = function () {
$.ajax({
url: "some url",
data: somedata,
dataType: "json",
_this: this,
success: function ( data ) {
// update data
var _this = this._this
_this.data1 = data.data1;
_this.data2 = data.data2;
}
});
};
};
And then:
function Caller() {
this.data1 = 0;
this.data2 = 1;
this.makeRequest = function () {
$.ajax({
url: "some url",
data: somedata,
dataType: "json",
context: this,
success: function ( data ) {
// update data
this.data1 = data.data1;
this.data2 = data.data2;
}
});
};
};
In all the cases above, it seems that a copy of the object, rather than the original one, is being pass to the function, so the original values are not
changed.
Is there a way to change the originals values of the object or pass the original one? I hope you can help me, i've stuck with this for a while.
If you send a request to another site, you must do
crossDomain: true
or
If you want to do data return, you must do
async: true
Example:
var data_1 = 0;
ajax success function data_1 = data.data_1
return data_1;
The alert at the start shows "undefined", why?
The alerts come in this order:
"success!"
"Data" (what it should be)
"undefined"
I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!
Very grateful for any help!
I got this code
var data = getData("");
alert(data); <<<<<<< UNDEFINED
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
function processData(data) {
var arrData = CSVToArray(data);
dimensions = arrData[0];
var objects = [];
objects[0] = dimensions;
for (var i = 1; i < arrData.length; i++){
objects[i] = new Object();
for (var j = 0; j < dimensions.length; j++){
objects[i][dimensions[j]] = arrData[i][j];
}
}
return objects;
}
To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.
Your getData function doesn't return anything.
You need to return it from the function itself.
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
^ This returns the data within getData. But getData doesn't do anything with it: such as returning it.
function getData(fileName) {
var ourData = "";
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
ourData = arrData;
},
});
return ourData;
}
This returns the data from getData to whatever calls that function.
edit: also, don't use async:false. Your browser won't capture any events happening until that AJAX completes. The benefit of asynchronous JS is that...we can! And in this case should.
Preface: Don't use async: false. But answering the question:
getData doesn't return anything. You're doing a return from the success callback, but that returns something from the success callback, not getData.
To change it so getData returns something, you'd do this:
function getData(fileName) {
var arrData;
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
arrData = processData(data);
},
});
return arrData; // <=== Now `getData` returns something
}
But don't do that. Instead, embrace asynchronous programming and remove async: false. For instance, a callback:
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
});
}
...called like this:
getData(function(data) {
alert(data);
});
...or a promise ($.ajax returns one, of sorts):
function getData(fileName) {
return $.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
}).then(data) {
return processData(data); // <== Becomes the resolution value of `getData`'s promise
});
}
and then
getData().then(function(data) {
alert(data);
});
data is undefined because the function getData doesn't return anything. You should have a look at promises.
I have multiple values, I am trying pass all values in url to controller class at one time.
But last value passed in url.
function submitFormData(formData) {
var x = [];
for(var i = 0;i < formData.length ;i++ ){
alert(i);
x = [];
x.push(formData[i].name);
x.push(formData[i].email);
x.push(formData[i].message);
}
var url= '/userrecords?x='+x;
alert(url);
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
controller class
#RequestMapping(value = "/userrecords")
public #ResponseBody StatusResponse saveList(#RequestParam(required = false) String x,Model model)
throws ParseException, SQLIntegrityConstraintViolationException {
//read all values here
}
What is wrong in my code. And how to read all values in controller.
Convert your array output in JSON and send it to using AJAX and also you have to define content type is JSON.
you can also use jquery ajax it is very simple for request response.
$.ajax({
type: "POST",
dataType: 'json',
url:"URL here",
success: function(data) // response
{}
});
I think you should post your formdata as ajax data as below.
Pass your x veriable as a ajax data.
function submitFormData(formData) {
var x = [];
for(var i = 0;i < formData.length ;i++ ){
alert(i);
x.push(formData[i].name);
x.push(formData[i].email);
x.push(formData[i].message);
}
var url= '/userrecords';
alert(url);
$.ajax({
type: 'POST',
data: x,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
I am loading 2 XML documents that both run functions on success, although the function for the 2nd XML document is dependant on the 1st being complete.
If I have async:true:
1st XML
function XmlDataTypes() {
var result = null;
var scriptUrl = "http://domain.com/xml/test.XmlDataTypes?AccountId=" + AccountId;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//create array to be used in second XML
for (var i = 0; i < xmlRows.length; i++) {
var dataType = xmlRows[i];
var dataTypeId = nodeValue(dataType.getElementsByTagName("DataTypeId")[0]);
var dataTypeName = nodeValue(dataType.getElementsByTagName("DataTypeName")[0]);
dataTypeArray.push({ dataTypeId: dataTypeId, dataTypeName: dataTypeName, position: i, markerArray: [] });
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
return result;
}
2nd XML
function XmlAmenityData() {
var result = null;
var scriptUrl = "http://domain.com/xml/test.XmlAmenityData?AccountId=" + AccountId;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//store this info in markerArray in dataTypeArray
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
return result;
}
The XML data can loaded in a random order so the function for the second document will error if the 1st hasn't completed.
If I set:
async: false
It works correctly but I get a warning:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
Is there a way around this without using:
async: false
Since the 2nd xml is dependent on the 1st, you can define a callback on success.
Also since ajax is async, you must assign the result when the callback is called. You can define a variable ourside of your function (in this case an array) and put the data there.
var result = [];
function XmlDataTypes(url, accountId, callback) {
var scriptUrl = url + accountId;
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
// do something
result.push(data);
if(typeof callback == 'function') {
callback();
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
}
function doSomething() {
// Do something to store this info in markerArray in dataTypeArray
// XmlAmenityData is in results var.
}
And you can use it like so
var _callback = XmlDataTypes("http://domain.com/xml/test.XmlAmenityData?AccountId=", "1234", doSomething);
XmlDataTypes("http://domain.com/xml/test.XmlDataTypes?AccountId=", "1234", _callback);
EDIT: Updated script based on given scenario.
You could try to return the $.ajax as a promise:
function XmlDataTypes() {
// note domain.com was changes to example.com - this should be changed back
var scriptUrl = "http://example.com/xml/test.XmlDataTypes?AccountId=" + AccountId;
return $.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'xml',
async: true,
success: function (data) {
//create array to be used in second XML
for (var i = 0; i < xmlRows.length; i++) {
var dataType = xmlRows[i];
var dataTypeId = nodeValue(dataType.getElementsByTagName("DataTypeId")[0]);
var dataTypeName = nodeValue(dataType.getElementsByTagName("DataTypeName")[0]);
dataTypeArray.push({ dataTypeId: dataTypeId, dataTypeName: dataTypeName, position: i, markerArray: [] });
}
},
error: function onXmlError() {
alert("An Error has occurred.");
}
});
}
Then calling them in sequence :
XmlDataTypes.done(XmlAmenityData);
Here is some more documentation :
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html