I have first PHP file where I have form and it's action is directing me to next php file. The code snippet is as below:
<form name="drugForm" action="drug_form2.php" onsubmit="return validateForm()" method="post">
In function validateForm (javascript) I am checking whether text area is filled and at least a checkbox is checked. And I am creating array, here in javascript, to get checkbox values. The js code is below:
function validateForm()
{
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
var y_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);
}
}
for(m=0;m<y.length;m++)
{
if(y[m].checked)
{
for(l=0;l<y_array.length;l++)
{
alert("This is array " + y_array[l]);
}
dataString = y_array ; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "drug_form2.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
//alert("The array length is " + y_array.length);
//return true;
}
}
alert("Check one checkbox at least");
return false;
}
}
Here, from this function I want send array to php, for this reason I referred following link but it didn't work:
Send array with Ajax to PHP script
Now, my queries are as following:
Why am I not able to print array value inside second for loop? and How can I access javascript array in PHP file?
I have PHP file too to check whether array values are printing properly, but it is not giving those values. Below is second PHP file to get javascript array in PHP file:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
echo "Its in form2 and working fine";
?>
</body>
</html>
Am I including ajax function at right place?