Reputation: 63299
I am using $.ajax to post data to the server. However I want to pass an additional parameter to the 'success' callback to tell the callback function the id of the HTML element the response is for.
It is possible? Like:
success_cb(data, elementid)
{
(update the elementid with the server returned data)
}
$.ajax({
...
success:success_cb(elementid)
});
Upvotes: 17
Views: 15710
Reputation: 2621
This might be a late post, but there is another option that worked for me.
On the Ajax object I added more variables, for example variableNeeded:
$.ajax({
url:"url.php",
method:"post",
variableNeeded:"ABC123",
dataType:"json",
error:function(){
// manage error
},
success:function(json,status,xlr){
console.log(this.variableNeeded);
// use variable as needed.
}
});
Because is part of the object it will be available inside the success function by using this ex: this.variableNeeded
Upvotes: 1
Reputation: 303188
function postForElement(elementId){
$.post('/foo',someValues,function(data){
$(elementId).html("The server returned: "+data);
},'json');
}
By declaring the function literal in the same scope as the elementId
local variable, the function becomes a closure that has access to that local variable. (Or some might say it only becomes a closure when the function literal also references the non-global variable that is not defined in its scope. That's just bandying with words.)
Upvotes: 13
Reputation: 3284
It is possible. Try something like:
function success_cb(data, elementid)
{
(update the elementid with the server returned data)
}
$.ajax({
...
success:function(data){ success_cb(data, elementid); }
});
Upvotes: 25