Reputation: 703
I want to know how to pass value from ajax function to another ajax I've tried this code but It does not work. Anyone know how to do it the right way? Thanks!
$("#button").click(function(){
var passedValue = '';
$.ajax({
url://
type://
success:function(data){
if(typeof==="object"){
for(var i=0;i<data.length;i++){
passedValue = data[i]["passedThis"];
}
}
}
});
$.ajax({
data: { receivedPassed: passedValue;}
});
});
Upvotes: 0
Views: 2065
Reputation: 91299
Chain the AJAX calls using .then()
, and filter data from the first call to the second using .pipe()
:
$("#button").click(function() {
$.ajax({
url: //
type: //
}).pipe(function (data) {
var passedValue = [];
for (var i = 0; i < data.length; i++) {
passedValue[i] = data[i]["passedThis"];
}
return passedValue;
}).then(function (receivedPassed) {
$.ajax({
data: { receivedPassed: passedValue }
}
}
});
Also note that the .success()
callback will be deprecated in jQuery 1.8:
Deprecation Notice: The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callbacks will be deprecated in jQuery 1.8.
Upvotes: 1
Reputation:
Those requests are asynchronous, so passedValue
isn't ready by the time the second one is sent. You'll probably want to send them in order:
$("#button").click(function() {
$.ajax({
url: //
type: //
success: function(data) {
var passedValue;
if(typeof (?) === "object") {
for(var i = 0; i < data.length; i++) {
passedValue = data[i]["passedThis"];
}
$.ajax({
data: { receivedPassed: passedValue }
});
}
}
});
});
Also, you're overwriting passedValue
each time through that loop. Did you mean +=
instead of =
, or to use an array, or something?
Upvotes: 2