Dynamically include properties of a $.ajax function

Asked

Viewed 186 times

4

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

When the date variable 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 to omit the "date" property altogether. I also haven’t found anything similar.

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

Thank you.

1 answer

5


This is simple, notice that what you pass to the ajax function is an object. Set it outside the function invocation and it’s easy to add this property if you need to, 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 wanted, where it just adds data case parametro valide true.

  • and here I am thinking of making a IIFE, store $.ajax in a local variable closure, and return a function that deletes the date property if it is empty. and this function overwrites the $.ajax global.

  • 1

    Good Sergio. Worked as expected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.