Include properties of a $ .axax function dynamically

3

Is there any way to edit the $ .ajax function so that it includes the "date" property when it receives a value, and removes it when it does not receive it? that is, dynamically? Example:

When the variable date has value:

var parametro = "{id: "1"}";

      $.ajax({
            type: "POST",
            url: url,
            data: parametro ,
            async: async,
    ...

When it has no value:

var parametro = "";

     $.ajax({
            type: "POST",
            url: url,
            async: async,
    ...

So my idea is something that works like:

 $.ajax({
            type: "POST",
            url: url,
            if(parametro)
            {
               data: parametro,
            },           
            async: async,
    ...

I've tried to pass as:

data: undefined ,
data: "",
data: null ,

But nothing works. The only way is bypassing the "data" property altogether. I also did not find anything similar.

One more thing, building two versions of the function, as above, is not an option! I need to do dynamically.

Thank you.

    
asked by anonymous 20.07.2016 / 08:17

1 answer

4

This is simple, note that what you pass to the ajax function is an object. Set it out of the invocation of the function and it's easy to add this property if you need it, like this:

var config = {
    type: "POST",
    url: url,
    data: parametro ,
    async: async,
    ...

if (parametro) config.data = parametro;
$.ajax(config);

In this line if (parametro) config.data = parametro; you have the logic you want, where only adds data if parameter validates true .

    
20.07.2016 / 09:11