Send post with multiple values through Jquery

Asked

Viewed 108 times

0

I have this Jquery code to send a Post.

var formTest = document.createElement('form');
formTest.setAttribute("method", "post");
formTest.setAttribute("action", "");
var post = document.createElement("input");
post.setAttribute("type", "hidden");
post.setAttribute("name", "idsTransf");
post.setAttribute("value", "25");
formTest.appendChild(post); 
document.body.appendChild(formTest);
formTest.submit();

In this case, I send a post with the value of "idsTransf". How do I send the post with multiple values, through this code?

1 answer

1

From the data in the form

post.id = "submit";

First you will need to get the data from this form, right after making the append in the document

var _url = "caminho/para/o/arquivo.php"
var _data = new FormData($("#submit")[0]);

So you can use ajax function from the form

$.ajax({
        url: _url,
        type: 'POST',
        data: _data,
        timeout: 20000,
        processData: false, 
        contentType: false,
        success: function (data) {
            //Código para resposta da requisição
        }, error: function(data){
            //Código para falha na requisição
        });

processData: false and contenttype: false -> does not transform date into Json format for Formdata, as it is already a Formdata

You can also pass an array but must use the following code

$.ajax({
        url: _url,
        type: 'POST',
        data: {name1:array(valor1,valor2),name2:array(valor3,valor4)},
        timeout: 20000,
        success: function (data) {
            //Código para resposta da requisição
        }, error: function(data){
            //Código para falha na requisição
        });

processData and contenttype -> in the default configuration transforms date into Json format for Formdata

In case it is not necessary to create the form

Browser other questions tagged

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