Tom
Tom

Reputation: 2661

Reuse the same AJAX calls

I have a couple of ajax requests to urls that are very similar, but are supposed to do different things with the responses at different points. So instead of writing a new ajax call every time I need it, I am trying to reuse the ajax calls as a function with parameters:

function createAjaxObj(type,name,id,successFunc){
    var config = {
        url: MY_URL,
        type: type,
        data: {
            name : name,
            id : id,
        },
        headers: { "X-CSRFToken": returnCsrfToken(); },  
        success: successFunc,
        error: function(xhr,ajaxOptions, thrownError) { console.log('error=',xhr);},
    };  
    $.ajax(config);
}

So now, I am planning on calling this function every time I need it like that:

var myFunc = function(context){console.log(context)}
createAjaxObj("GET","MyName",58,myFunc)

I was wondering if this is a good idea or common practice or is there an easier way to achieve this?

Upvotes: 1

Views: 1104

Answers (2)

dhilt
dhilt

Reputation: 20744

I would do it in a Promise way:

 function myAjax(type, name, id) {
    return $.ajax({
      url: MY_URL,
      type: type,
      data: {
        name : name,
        id : id,
      },
      headers: { "X-CSRFToken": returnCsrfToken(); })
    })
    .fail(function(){
      console.log('error');
    });
  }

  var myFunc = function(context){ console.log(context); };
  myAjax("GET", "MyName", 58).then(myFunc);

Upvotes: 1

stevenlacerda
stevenlacerda

Reputation: 1187

You can make it a promise, if what you're doing with the response changes:

function createAjaxObj(type,name,id,successFunc){
  return $.ajax({
     url: MY_URL,
     type: type,
     data: {
       name: name,
       id: id
     }
  })
}

now you can run it like so:

createAjaxObj('foo', 'bar', 1)
  .then(function(data) { // do something with data })
  .error(function(err) { // do something with error })

I think that should work for you. Let me know if not, I'll create a fiddle for it.

Upvotes: 1

Related Questions