RaTiO
RaTiO

Reputation: 1049

Parametrizable success function for jQuery ajax call

I want to create a function to call the jQuery $.ajax function with a parameter that indicates the success function name that must be called after the success event.

Something like this, but I don't know how to fill the "complete" parameter, or even if it's possible to do this:

function callService(successFunctionName){
$.ajax({
 url: "serviceURL",
 type: "POST",
 data: "request",
 contentType: "text/xml; charset=\"utf-8\"",
 complete: successFunctionName
});

}

succesFunction1(){
}

successFunction2(){
}

Edit: I have to clarify that successFunctionName is an string

Upvotes: 1

Views: 312

Answers (3)

Samba
Samba

Reputation: 605

I think you want to have call back for Ajax success, not complete ?

For success :

 $.ajax({
   ......    
   success: successFunctionName

  });  

For complete :

  $.ajax({
   ......    
  }).done(function(){
     successFunctionName();
  });

Upvotes: 0

Gavin
Gavin

Reputation: 6394

What you've done is correct.

When calling your callService you would do:

callService(function(resp)
{
    alert('Success: ' + resp);
}):

Upvotes: 0

Andreas
Andreas

Reputation: 21881

If successFunctionName is a string you could then use window[successFunctionName]. If it is the function itself it should work already

function callService(successFunctionName) {
    $.ajax({
        //...
        complete: (typeof successFunctionName === "string" ? window[successFunctionName] : successFunctionName)
    })
}

Upvotes: 1

Related Questions