gree_tejas
gree_tejas

Reputation: 45

Passing of JSON array to PHP file using javascript AJAX function

I am now about to give up for ajax in javascript to pass JSON array to PHP. I have first PHP file in which I have form which contains a text area and checkboxes. The snippet is below:

  <form name="drugForm" onsubmit="return validateForm()" method="post">
Drug name: <input type="text" name="dname"></pre>
  <pre>

<input type="checkbox" name="drug" value="one">1    <input type="checkbox" name="drug" value="two">2</br>
<input type="checkbox" name="drug" value="three">3  <input type="checkbox" name="drug" value="four">4</br></br>
    <input type="submit" value="Submit">
  </pre>

Here, with validateForm() call I am calling javascript to check whether text area is filled and at least a checkbox is checked. Also, it is creating array, in javascript, to get checked values. Here with this js I want to send this array to PHP file by converting it JSON using ajax. COde snippet is below:

 function validateForm()
 {
  var x=document.forms["drugForm"]["dname"].value;
  var y=document.drugForm.drug;
  var y_array = new Array();

   if (x==null || x=="")
   {
alert("First name must be filled out");
return false;
   }

   else if (Boolean(x))
   {
 for(k=0;k<y.length;k++)
 {
    if(y[k].checked)
    {
        var arr_val = y[k].value;
        y_array.push(arr_val);
        //alert(arr_val);
    }

}
   $.ajax({
    type: "POST",
    url: "drug_form3.php",
    dataType: 'json',
    data: {json: JSON.stringify(y_array)},
        });

alert("Check one checkbox at least");
return false;
  }
 }

Here, with js array is getting created and whenever I am printing values with alert, it is giving proper result. But, when I am trying to send it to next PHP file even after using json_decode in php file, it is not able to get array printed with PHP. Below is code snippet for second PHP:

 <body>
 <?php
 $json = $_POST['json'];
 $array=json_decode($_POST[$json]);

  // here i would like use foreach:

  print_r ($array);
  echo "Its in form2 and working fine";
 ?>
 </body>

Please guide me in this issue, how to pass json array to PHP file using javascript.

Upvotes: 0

Views: 1629

Answers (3)

Anil Saini
Anil Saini

Reputation: 637

Try this and see if it works for you

$array = json_decode($_POST['json'], true);

Upvotes: 0

Krish R
Krish R

Reputation: 22711

Can you try this and check whether you getting the post values here,

 $json = $_POST['json'];
 echo "<pre>"; print_r($json);echo "</pre>";

Upvotes: 0

user2417483
user2417483

Reputation:

You have the following lines confused:

 $json = $_POST['json'];
 $array=json_decode($_POST[$json]);

Change to:

 $array=json_decode($_POST['json']);

Upvotes: 1

Related Questions