Passing loop data via ajax data

My form contains a hidden input loop. in my case i am declaring hidden ajax data input manually without loops. so how to encode them in the ajax data?

here's my script form

<form method="POST" name="myform">
   <?php for($i=1;$i<=5;$i++) { ?>
            <input type="hidden" name="data<?php echo $i; ?>" value="data<?php echo $i; ?>">
   <?php } ?>
   <input type='button' name='submitData' value='Submit' onClick='submitData();'>
</form>

      

here's my Ajax script

function submitData() {
   var form = document.myform;
   $.ajax({
     url: 'process.php',
     type: 'post',
     data: {
          data1 : form["data1"].value,
          data2 : form["data2"].value,
          data3 : form["data3"].value,
          data4 : form["data4"].value,
          data5 : form["data5"].value
     },
     success: function (result) {
          console.log(result);
     },
     error: function () {
          console.log("error");
     }
  });
}

      

+3


source to share


3 answers


Your hidden inputs have name and values,

use .serialize()

Encode a set of form elements as a string to submit

data : $('form[name=myform]').serialize()

      

This will bring back the vapors name=value

.



If you need {name:value}

use.each()

var formData = {}
$('form :input:hidden[name^="data"]').each(function(){
    formData[this.name] = this.value;
});

      

And in ajax,

data : formData ,

      

Demo

+3


source


If you are posting the whole form you can use jQuery directly . serialize () in your request:



$.ajax({
    url: 'process.php',
    type: 'post',
    data: $('#myform').serialize(),
...

      

+2


source


Also, a good way to do this is to convert a string to a JSON object, and in PHP, it is to convert a string to an array:

var dataJSON = JSON.stringify({..Your form obj...});

$.ajax({
    url: 'process.php',
    type: 'post',
    data: dataJSON,
    success: function (result) {
            console.log(result);
    },
    error: function () {
            console.log("error");
    }
});

      

process.php

$data = json_decode($_POST["data"]);
print_r($data);

      

+1


source







All Articles