-1

I am using following ajax utility function to make requests

function ajaxHandler(url, data)
{
    return new Promise(function (resolve, reject) {
        $.ajax({
            type: 'POST',
            url: url,
            dataType: 'json',
            data: data,
            success: function (data) {
                resolve(data);
            },
            error: function (xhr, textStatus, error) {
                reject(error);
            },


        });
    })

}

The default settings works great most of the time, but there are quite a few cases where I would like pass additional parameters like processData and contentType. How can pass processData and contentType for such cases ?

Cody
  • 2,480
  • 5
  • 31
  • 62

2 Answers2

3

Assuming that options is the object you want to pass in; moving the config object out of the function is about the cleanest. Then use $.extend to update the defaults

function ajaxHandler(url, data, options) {

  var config = {
    type: 'POST',
    url: url,
    dataType: 'json',
    data: data
  }

  if (options && $.type(options) == 'object') {
    $.extend(config, options);
  }

  return $.ajax(config)// add a global error handler if desired
}

Usage :

ajaxHandler('path/to/server', {foo:'bar'), {type:'GET'})
  .then(function(data){
     console.log(data);
  }).fail(function(){// or `catch` in jQuery version >=3
     // handle error
  })

Note that $.ajax returns a "thenable" promise so using new Promise is an anti-pattern. See What is the explicit promise construction antipattern and how do I avoid it?

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

I'm not sure if I got it right, if you like to add and override settings of the object you can use $.extend

function ajaxHandler(url, data, extraSettings)
{
    return new Promise(function (resolve, reject) {
        $.ajax($.extend({
            type: 'POST',
            url: url,
            dataType: 'json',
            data: data,
            success: function (data) {
                resolve(data);
            },
            error: function (xhr, textStatus, error) {
                reject(error);
            },


        }, extraSettings));
    })

}

This way $.extend(obj1, obj2) returns obj1 adding or overwriting properties of obj2.

you can use it like: ajaxHanler("url", "data", { contentType: "text/plain" });

DarioDF
  • 301
  • 1
  • 10