How to send two forms in a request via Ajax

Asked

Viewed 83 times

2

I have some fields on a page, which I can not put in a single form because of the distance between the codes, so I grouped in two languages that I need to send via Ajax.

ex:

<form id="form1">
<input type="text" name="nome" />
</form>

<form id="form2">
<input type="text" name="telefone" />
</form>

The above forms are hypothetical, since mine have many fields.

I have tried to group the two forms with . serialize() and Formdata() but was unsuccessful.

ex:

$("#form2").submit(function(e) {
        e.preventDefault();
     
        var pessoas = document.getElementById('form1');
        var telefones = document.getElementById('form2');

        formData = new FormData(pessoas);
        formData.append('tel', telefones);

        $.ajax({
            url: "<?= BASE_URL ?>ajax/teste",
            method: "POST",
            data: formData,
            dataType: 'json',
            contentType: false,
            cache: false,
            processData: false,
            success: function(response) {
                $('#resultado').val(response.mensagem);
            },
        });
})

In PHP I can receive the field name of Form1, but I can’t receive any field from form2

  • will not be able to post two Forms using an Object on the date, could create an object, for example var dados = { form1: new FormData(form1), form2: new FormData(form2) }, but if post this I think php will not be able to do POST to read

  • @Same error, form2 is not sent.

1 answer

1


I believe it is not possible to send two forms by AJAX request, but I have a suggestion

Any fields you send to AJAX, add a class to it, example "form-search".

In your AJAX function, search all fields that contain this class and store in an array

var ArrayDados = {};
$('.form-buscado').each(function(){
         ArrayDados[this.id] = this.value;
 });

In your AJAX, pass the array

data: {
    dados: ArrayDados
}

And in PHP you will receive an ARRAY and can access them with the input ID.

Example:

$VALORES_INPUT = $_POST['dados'];

$valor_cidade = $VALORES_INPUT['id_cidade'];

Browser other questions tagged

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