Get ajax result in foreach - javascript

I try to load data from service yelp, no problem with the request, but I can't push it to array and return it.
I need to get ajax result in every iteration.
How to stop it until ajax result has received?
can anyone help me?
this.getDataForPlaces = function(addresses){
var locationDescs = [];
_.each(addresses, function(address){
var promise = getLocationDesc(address).then(function(data) {
locationDescs.push(data);
});
})
return locationDescs;
};
var getLocationDesc = function(address){
var parameters = [];
var message = {
'action' : 'http://api.yelp.com/v2/search',
'method' : 'GET',
'parameters' : parameters
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
return $.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
console.log(data);
}
});
};

You have to return the data variable instead of ajax function like this : replace the following
return $.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
console.log(data);
}
});
with
$.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
return data;
}
});
for pausing / stoping the loop until the ajax request completes you can replace the following :
var promise = getLocationDesc(address).then(function(data) {
locationDescs.push(data);
});
with
var promise = $.when(getLocationDesc(address)).done(function(data){
locationDescs.push(data);
});
if above does not work then use the following and replace the whole loop with following
var locationDescs = [];
_.each(addresses, function(address){
locationDescs.push(getLocationDesc(address));
});
$.when.apply($,locationDescs).done(function(){
});
Don't return complete ajax function , just inside the success function of ajax return the data like this : return data; because return whole ajax function it is not an data that you are getting from services , you have to return data variable.

Related

why the parameter read by true?

i have tried to call variable $hetest but it always return with true however i add false as a parameter when i am calling the function
//function which i call in javascript file
create_new_user_send_sms(user_Mobile_Number,false)
.fail(error => console.error(error))
.done(response => {})
//the ajax call of the function i created
function create_new_user_send_sms(mobile_number,hestatus){
return jQuery.ajax({
type : "POST",
url: ajax_object.ajax_url,
data: {
action : 'create_user_send_sms',
mobile_number : mobile_number,
auto_Login_status : "true",
he : hestatus,
},
success: function (data) {
},
error : function(error){
console.log("error:" + error);
}
});
}
//the code in the php function create_user_send_sms
$mobile_number = $_POST['mobile_number'];
$auto_Login_status = $_POST['auto_Login_status'];
$hetest = $_POST['he'];
$password = wp_generate_password( 4, false, false );
Try using the filter_validation function to treat boolean post vars:
$hetest = filter_var ($_POST['he'], FILTER_VALIDATE_BOOLEAN);

Javascript async loop with ajax call

I have a jQuery ajax call that I want to do some task in order after the result comes.
$.ajax({
url : 'https://api.spacexdata.com/v3/launches',
type : 'GET',
dataType:'json',
success : function(data) {
data.forEach(async function(element) {
await console.log(element.flight_number);
await auto(element.flight_number);
});
},
error : function(request,error) {
console.log(request,error);
}
});
function auto(val) {
$.ajax({
url : 'https://api.spacexdata.com/v3/launches/latest',
type : 'GET',
dataType:'json',
success : async function(data) {
await console.log('second api called' , data);
},
error : function(request,error) {
console.log(request,error);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
the out put is :
1
2
3
4
...
second api called Obj
second api called Obj
second api called Obj
second api called Obj
...
but the expected result is :
1
the second api called
2
the second api called
3
the second api called
4
the second api called
....
here is the jsfiddle:
Do you have any idea what is wrong with the loop? I want the sequence I mentioned!
Can you try this code
$.ajax({
url : 'https://api.spacexdata.com/v3/launches',
type : 'GET',
dataType:'json',
success : function(data) {
data.forEach(function(element) {
console.log(element.flight_number);
auto(element.flight_number);
});
},
error : function(request,error) {
console.log(request,error);
}
});
async function auto(val) {
const dataset= $.ajax('https://api.spacexdata.com/v3/launches/latest');
console.log('second api called');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ajax call to spring controller callback error function

Can you tell me what it's going wrong with the following ajax call to controller ?
The controller that is called via ajax :
#RequestMapping(value = "/userManagement/loadData.html", method = RequestMethod.POST,produces="text/plain")
public #ResponseBody String loadData(#RequestBody String jsonData) {
try {
Map<String, Object> data = JsonUtils.jsonAsMap(jsonData);
pageSize = Integer.valueOf(data.get("pageSize").toString());
pageNumber = Integer.valueOf(data.get("pageNumber").toString());
} catch (Exception e) {
return "failure";
}
return "success";
}
The ajax function :
function reloadUsers(){
$.ajax({
type : "POST",
cache : false,
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
url : "userManagement/loadData.html",
data : JSON.stringify({
pageSize : 10,
pageNumber : 0
}),
success : function(response) {
if(response.responseText=='true'){
console.log('success');
}else{
console.log('server error');
}
},
error : function(jqxhr){
console.log('error');
console.log(jqxhr.responseText);
}
});
}
Now when i execute the ajax call to the controller it always goes on the error function and the jqxhr.responseText is always the value returned by the controller(in this case 'success' or 'failure'.
My question is why is this happening ?
If i change the controller returned values to "true" or "false" the ajax successfully callback the 'success' function.
I also tried with produces="application/json"and got the same result.
Change the datatype to:
dataType: 'text',
As you are going to get a string in response because of this:
#RequestMapping(value = "/userManagement/loadData.html", ....... produces="text/plain")
//--------because of this-----------------------------------^^^^^^^^^^^^^^^^^^^^^^

variable getting output before it's value is updated by a function

I have the following code that outputs the initialized value of my variable before it is updated by an $.ajax() callback. It seems that the 'get' is performed after the variable is logged despite how the code is written. How can I correct this? Thanks for any suggestions.
var statusUpdate = {
queries : [],
numQueries : 0,
getNumQueries : function(){
$.ajax({
type: 'get',
url: '40985839503175/planXML.txt',
cache: false,
error: function()
{
},
success: function(data){
statusUpdate.queries = $(data).find('query');
statusUpdate.numQueries = statusUpdate.queries.length;
//console.log(statusUpdate.numQueries);
}
});
} // end getNumQueries
};
statusUpdate.getNumQueries();
console.log(statusUpdate.numQueries)
var statusUpdate = {
queries : [],
numQueries : 0,
getNumQueries : function(){
$.ajax({
type: 'get',
url: '40985839503175/planXML.txt',
cache: false,
error: function()
{
},
success: function(data){
statusUpdate.queries = $(data).find('query');
statusUpdate.numQueries = statusUpdate.queries.length;
console.log(statusUpdate.numQueries);
}
});
} // end getNumQueries
};
Uncomment the logger in the success callback. Otherwise the log may run before the ajax call gets a chance to complete.
Ajax calls are asynchronous. I'm guessing that you are seeing 0 in your console?
Put the console.log inside the success function. But I'd recommend passing a callback or returning the promise object (it will require you to restructure your JavaScript).
var statusUpdate = {
queries : [],
numQueries : 0,
getNumQueries : function(){
$.ajax({
type: 'get',
url: '40985839503175/planXML.txt',
cache: false,
error: function()
{
},
success: function(data){
statusUpdate.queries = $(data).find('query');
statusUpdate.numQueries = statusUpdate.queries.length;
console.log(statusUpdate.numQueries)
}
});
} // end getNumQueries
};
statusUpdate.getNumQueries();
UPDATE: Here's what I meant by using a promise. For more info, see Deferred Object and the jQuery.ajax() documentation
var statusUpdate = {
queries : [],
numQueries : 0,
getNumQueries : function(){
var deferred = new $.Deferred();
$.ajax({
type: 'get',
url: '40985839503175/planXML.txt',
cache: false
}).done(function(data){
statusUpdate.queries = $(data).find('query');
statusUpdate.numQueries = statusUpdate.queries.length;
deferred.resolve();
).fail(function () {
deferred.reject();
});
return deferred.promise();
} // end getNumQueries
};
statusUpdate.getNumQueries().done(function () {
console.log(statusUpdate.numQueries)
});
Ok, I guess I can't make it work as envisioned. I added a complete function but it seems like kind of a workaround. Is this a reasonable practice? Thanks.

How to get data from ajax call?

I am trying to get data from ajax call by cross domain.
Here is code
function GetMaxWULen() {
var x;
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).done(function(result) {
console.log('done result');
x = result;
console.log(x);
});
console.log('function end');
console.log(x);}
At the end of the function, x variable is undefined but in done event value is correct.
Could anyone can help me or tell what is wrong in this code?
This happens because your AJAX request is done asynchronously. It means the rest of your code won't wait your response be ready to continue.
If you need to use the data returned from AJAX outside your function, you might want to create a parameter to serve as a callback when the response is ready. For example:
function yourFunction(callback) {
$.ajax({
/* your options here */
}).done(function(result) {
/* do something with the result here */
callback(result); // invokes the callback function passed as parameter
});
}
And then call it:
yourFunction(function(result) {
console.log('Result: ', result);
});
Fiddle: http://jsfiddle.net/9duek/
try
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).success(function(result) {
var datareturned = result.d;
console.log('done' + datareturned);
x = datareturned;
console.log(x);
});

Categories