jQuery AJAX custom function and custom callback?
Asked Answered
D

3

6

Heylow everyone!

I have an ajax() call like so:

$.ajax({
  type: "post",
  url: "whatever.php",
  data: {
    theData: "moo moo"
  },
  success: function(data) {
    console.log(data);
  }
});

Is it possible to wrap this inside a custom function but retain the callback?
Something like:

function customAjax(u, d, theCallbackStuff) {
  $.ajax({
    type: "post",
    url: u,
    data: d,
    success: function(data) {
      //RUN theCallbackStuff
    }
  });
}

theCallbackStuff will be something like:

var m = 1;
var n = 2;
alert(m + n + data);
Daradarach answered 10/10, 2012 at 13:58 Comment(3)
did you try it? I would imagine this would be possibleFimbriation
So, can I hold a complete function within theCallbackStuff ?Daradarach
I'm at work at the moment, so I can't try it - I was theorising in my head ;)Daradarach
L
11

EDIT:

Got a recent upvote for this and I feel compelled to state that I would no longer do it this way. $.ajax returns a promise so you can do pretty much what i just did here in a more consistent and robust way using the promise directly.

function customRequest(u,d) {
   var promise = $.ajax({
     type: 'post',
     data: d,
     url: u
   })
   .done(function (responseData, status, xhr) {
       // preconfigured logic for success
   })
   .fail(function (xhr, status, err) {
      //predetermined logic for unsuccessful request
   });

   return promise;
}

Then usage looks like:

// using `done` which will add the callback to the stack 
// to be run when the promise is resolved
customRequest('whatever.php', {'somekey': 'somevalue'}).done(function (data) {
   var n = 1,
       m = 2;

   alert(m + n + data);
});

// using fail which will add the callback to the stack 
// to be run when the promise is rejected
customRequest('whatever.php', {'somekey': 'somevalue'}).fail(function (xhr, status, err) {
   console.log(status, err);
});

// using then which will add callabcks to the 
// success AND failure stacks respectively when 
// the request is resolved/rejected
customRequest('whatever.php', {'somekey': 'somevalue'}).then(
  function (data) {
     var n = 1,
         m = 2;

     alert(m + n + data);
  },
  function (xhr, status, err) {
     console.log(status, err);
  });

Sure i do this all the time. You can either execute the callback within the actual success callack or you can assign the callback as the success callback:

function customRequest(u,d,callback) {
   $.ajax({
     type: "post",
     url: u,
     data:d,
     success: function(data) {
        console.log(data); // predefined logic if any

        if(typeof callback == 'function') {
           callback(data);
        }
     }
  });
}

Usage would look something like:

customRequest('whatever.php', {'somekey': 'somevalue'}, function (data) {
   var n = 1,
       m = 2;

   alert(m + n + data);
});
Lapoint answered 10/10, 2012 at 14:5 Comment(3)
This is exactly what I was looking for - although shouldn't it be === ?Daradarach
you could do === but in this case it wont matter because the result of typeof will be a string.Lapoint
Best Edit I've seen all day. Thanks so much,...this is the way to go.Preceding
A
5
    function customAjax(u, d, theCallbackStuff) {
      $.ajax({
        type: "post",
        url: u,
        data: d,
        success: theCallbackStuff 
      });
    }

customAjax(url, data, function(data){
//do something
});
Autopsy answered 10/10, 2012 at 14:1 Comment(1)
I would make sure you check for existence of the function using: if(window.some_function_name_here) or if( typeof funcname == 'function' )Fimbriation
F
1

On this note, you can pass a complete function as a callback to this:

function customRequest(u,d,callback) {
   $.ajax({
     type: "post",
     url: u,
     data:d,
     success: function(data) {
        console.log(data); // predefined logic if any

        if(typeof callback == 'function') {
           callback(data);
        }
     }
  });
}



// Then call it as follows:

function initiator() {

    customRequest( '/url/to/post', 'param1=val', function() { alert( 'complete' ); })

}

Simply passing it as an anonymous function will work too.. Just for the sake of showing :)

Fimbriation answered 10/10, 2012 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.