Search code examples
javascriptjqueryasp.netajaxwebmethod

Passing jQuery object and WebMethod return value to an OnSuccess function


I am calling a WebMethod from this code:

if($(this).attr("checked")) {  
..  
MyWebMethod(variable1, variable2, onSuccessFunction);  
}

The MyWebMethod returns an integer, and I want to set $(this).attr("id") of the jQuery object above to the returned integer. Basically, I'm trying to do the equivalent of an MVC Ajax.ActionLink...AjaxOptions {UpdateTargetID =...} However, I can't figure out how to get both a reference to $(this) as well as the returned value. For example, if I do:

MyWebMethod(variable1, variable2, onSuccessFunction($(this)));

I can succesfully manipulate the jQuery object, but obviously it doesn't have the return value from the MyWebMethod. Alternatively, the first code block with a method signature of onSuccessFunction(returnValue) has the correct return value from MyWebMethod, but no concept of the jQuery object I'm looking for. Am I going about this all wrong?


Solution

  • I don't know exactly what parameters the onSuccessFunction in your first example is expecting, but something like this will be what you're looking for.

    if($(this).attr("checked")) {   
      var el = $(this); 
      MyWebMethod(variable1, variable2, function(x, y z) { onSuccessFunction(x, y, z, el); });   
    } 
    

    ** Update ** Fixed to avoid a "this" scoping issue.