简体   繁体   中英

Submission of form with array of input using AJAX not working

Click handler

$('.to-pay').click(function(e)
{
   var finputs=$('form.inputs-form').serialize();
   alert(finputs);
   $.ajax(
   {
       url: "URL_HERE",
       type:"POST",
       data: finputs,
       success: function(data)
       {
      $('.another-div').html(data);
       }
   });
});

PHP part

$pid=$_POST['pid'];
$size=$_POST['product-size'];
$quantity=$_POST['quantity'];


foreach($pid as $key => $prod_id)
{
  echo "This part is called";
  echo $prod_id." of size ".$size[$key]." ".$quantity[$key]." numbers.";
}

The problem is in the PHP side. The foreach() part is not getting executed. In the jQuery side I checked using alert() and the data looks like,

pid%5B%5D=1&product-size%5B%5D=100&quantity%5B%5D=10&pid%5B%5D=2&product-size%5B%5D=150&quantity%5B%5D=20

What is the problem in the PHP side?

dude, the alert what you are getting is a string

.serialize() Description: Encode a set of form elements as a string for submission.

Solution: Use .serializeArray() instead

$('form.inputs-form').serializeArray();

refer this http://api.jquery.com/serializeArray/

then at php side change code accordingly.

OR
At PHP side explode the $_POST['data'], so as to make it a php Array and then iterate the array using foreach

try:

$pid=$_POST['pid'];
$size=$_POST['product-size'];
$quantity=$_POST['quantity'];

$i = 0;
foreach($pid as $prod_id)
{
  echo "This part is called";
  echo $prod_id." of size ".$size[$i]." ".$quantity[$i]." numbers.";
$i++
}

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