Form submission and out-of-form array via post

Asked

Viewed 1,364 times

3

I have the following problem: I need to send via post the data of a form together with the data of an html table to which I mount a array javascript. Unfortunately, I have no idea how to proceed in this case.

I ask for help from colleagues in this challenge.

2 answers

1

Eric, we have two options:

  1. Serialize fields sent from fields using field name as prefix:

  2. Manually build array with fields sent using field name as prefix:

- WAY TO "SERIALIZE WITH A NAME PREFIX"

Be two fields with prefix "field"

<input type="text" name="campoNome">
<input type="text" name="campoEmail">

Then, we save in a variable the object containing the data of the fields:

var camposEnviados = $("input[name^='campo']").serialize();

- WAY "BUILD MANUALLY"

We can build the array manually (by selecting field by field its value):

var camposEnviados = [];
camposEnviados[0] = $('campoNome').val();
camposEnviados[1] = $('campoEmail').val();;

- SENDING VIA AJAX

$.ajax({
   type: "POST",
   data: {camposEnviados: camposEnviados},
   url: "index.php",
   success: function(msg)
   {
     $('.resposta').html(msg);
   }
});
  • Hi Felipe! Your idea and explanation helped me a lot in the final assembly of the process. I chose to launch the array in input value of type 'Hidden' and at the time of Submit. Thank you so much for your help! Big hug!

  • Eric, good morning! Glad you decided! Hug

1


You have two options,

  • send all via AJAX

  • send table data to a hidden input

If you send by ajax you can use the .serialize() jQuery and send in ajax something like this:

var fData = $('form').serialize();
$.ajax({
   type: "POST",
   data: {form: fData, table: JSON.stringify(tDada)}, // onde tData é a array da tua tabela
   url: "index.php",
   success: function(msg)
   {
     $('.resposta').html(msg);
   }
});

if you want to place this table data inside a hidden field:

<input type="hidden" name="tabela" id="dadosTabela" />

and then inject into the input value the table data:

$('dadosTabela').val(JSON.stringify(fData));
  • 1

    Sergio, you saved my project! Rs. I had already tried to put the array in the field type Hidden. But I had trouble taking advantage of the data after the post, on the php side. Your solution of sending it via JSON made the process functional. Thank you so much for the support! I owe you one!

Browser other questions tagged

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