Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery $.ajax: pass additional argument to 'success' callback

Tags:

jquery

ajax

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)
});
like image 467
Bin Chen Avatar asked Nov 17 '10 06:11

Bin Chen


2 Answers

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); }
});
like image 52
Horatio Alderaan Avatar answered Oct 24 '22 06:10

Horatio Alderaan


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.)

like image 21
Phrogz Avatar answered Oct 24 '22 07:10

Phrogz