3

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

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think it should be $('form :input[type="hidden"]')
@ShaunakD it works, but it will get all of the input hidden, i just want to get the chosen name and value in form, is it possible to do that? thankyou before.
Updated the code with $('form :input:hidden[name^="data"]')
2

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(), ... 

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.