简体   繁体   中英

passing looping data through ajax data

My form contains hidden input looping. in my case, i declare the hidden input in ajax data manually without looping. so how to loop them in ajax data?

here's my form script

<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");
     }
  });
}

Your hidden inputs have name and values,

use .serialize()

Encode a set of form elements as a string for submission

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

This will return name=value pairs.

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

If you're posting the whole form, you can use jQuery's .serialize() directly in your request:

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

Also, a good way to do it is to convert the string to JSON object, and in PHP convert the string in 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM