0

I’m trying to pass values from a dynamic form to PHP, using jQuery serialize(), but I am only receiving part of the string:

The form is created by a MySQL query:

echo '<form role="form" id="reserva_tour" action="shop_wopt.php" method="POST">';
 $db->Consultar("SELECT * FROM tour_options WHERE tourID = '$tour_id' order by tourID");    
while($row = $db->ObtenerArray()) {
    $regis   = $row['recid'];
    $name    = $row['name'];
    $radl    = $row['adl_rate'];
    print "<a href='#' class='tit_tour btn btn-success'>$name - $$ratebase</a>";
    print "<input type='text' name='open_adl[$regis]' id='adl$regis'  class='adl' />";
  }
  print "<a href='#' class='calcTourOpt btn btn-block">Tour Calc </a>";
  print "</form>";

The jQuery:

$(".calcTourOpt").click(function()
  {
      var adl = $('.adl').serialize().replace(/%5B/g, '[').replace(/%5D/g, ']');
      console.log(adl);
      $.ajax({
         url: "calctour_opt.php",
         data:"adl=" + adl + "", 
         type: "POST",
         dataType: "json",
         cache: false,
         success: function(data){
            console.log(data)
         }  
      });
    });

This is calctour_opt.php:

$adl   = $_POST['adl'];
$values = array();
parse_str($adl);   
$total = $open_adl[4]; 
echo json_encode($total);

This is happening:

After serializing the class "adl" (before the ajax call, in the console.log), the string looks like this: open_adl[4]=2&open_adl[5]=3 and is correct!

In my php file if I declare $total = $open_adl[4]; works fine, it shows me the result: 2.

But if I change to: $total = $open_adl[5]; does not work, it shows me NULL, instead of 3.

Can anybody tell me what is wrong?

1
  • Another silly question: How can I run print_r($open_adl) on the Ajax Call. As you see I'm sending the form to Jquery, then I made the Ajax call? Commented Dec 13, 2015 at 8:51

1 Answer 1

1

You should change $.ajax data param from string to json string like this

// FROM 
$.ajax({
     url: "calctour_opt.php",
     data:"adl=" + adl + "", //<- Wrong
     type: "POST",
     ...

// TO
$.ajax({
     url: "calctour_opt.php",
     data: {adl: adl}, //<- Correct

check documentation here about data param for ajax - http://api.jquery.com/jquery.ajax/

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

1 Comment

I'm sending the Form Input to Jquery as class 'adl' $('.adl') and then I made the ajax call with variable adl data:"adl=" + adl + ""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.