Pass parameters outside jQuery.Ajax

Asked

Viewed 35 times

0

Good evening, I wonder if there is a possibility to determine the parameters outside the + function - in this way?

Like, I’m saying that in var sintax the parameters of the function ajax before turning when re == 1 or not.

jQuery(document).ready(function(){

    jQuery('form._returnJson').submit(function(){
        var dados = jQuery( this ).serialize();
        var re    = $(this).attr("changeBut");

        if($re == 1)
            var sintax = {
                type: "POST",
                url: _url+"/config/server.php",
                data: dados,
                dataType: 'json', // obj.return obj.token obj.mensagem
                cache: false,
            }
        } else {
            var formulario = document.getElementById(this);
            var dados = new FormData(formulario);

            var sintax = {
                type: "POST",
                url: _url+"/config/server.php",
                data: dados,
                dataType: 'json', // obj.return obj.token obj.mensagem
                cache: false,
                processData: false,  
                contentType: false,
            }
        }

        jQuery.ajax({
            sintax,
            sucess: function(){},
        });

        return false;
    });

});

I need to determine two type of ajax, one for image upload and one for data, but I wanted to do this without creating two ajax, in a single understand?

1 answer

1


Yes, it’s possible, but the way you’re doing it, all the properties will stay inside the object sintax, that is, your code will be interpreted this way:

jQuery.ajax({
    sintax: {
        type: "POST",
        url: _url+"/config/server.php",
        data: dados,
        dataType: 'json', // obj.return obj.token obj.mensagem
        cache: false
    },
    sucess: function(){},
});

To pass only the properties of sintax, and not the whole object, use the operator ... to unstructure its object, in this way:

jQuery.ajax({
    ...sintax,
     sucess: function(){},
});

Thus the code will be interpreted as follows:

jQuery.ajax({
    type: "POST",
    url: _url+"/config/server.php",
    data: dados,
    dataType: 'json', // obj.return obj.token obj.mensagem
    cache: false,
    sucess: function(){},
});
  • It worked perfectly, thank you. ;)

Browser other questions tagged

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