I am creating Web application in which I have two different list. I have convert list into array and that array I want to pass from JavaScript to PHP for further analysis.
This is an Example which is similar to my original code
test_2.html
<form method="post" id="theform" action="test_2.php">
<ul id="control">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<ul id="treatment">
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
<button>Submit</button>
</form>
<script>
window.onload = function () {
var form = document.getElementById('theform');
var lst = [];
var lst2 = [];
form.addEventListener('submit', function () {
var lis1 = document.querySelectorAll('#control li');
for (var i = 0; i < lis1.length; i++) {
lst.push(+lis1[i].innerText);
}
var lis2 = document.querySelectorAll('#treatment li');
for (var i = 0; i < lis2.length; i++) {
lst2.push(+lis2[i].innerText);
}
var array = [lst, lst2]
$.ajax({
type: "POST",
url: "php/test_2.php",
data: {"data":array},
datatype: "json",
success: function(response){
alert("response " + response);
}
});
}
</script>
test_2.php
$sub_array = var_dump($_POST['data']);
echo $sub_array;
The problem is I am not able to pass the array. I have tried my thing and also did refer many question :-
how to use JSON.stringify and json_decode() properly
Passing Javascript array to PHP file
Get response from PHP file using AJAX and many more
3
Answers
You have some syntax error in Javascript and calling 2 times the page text_2.php, one in
<form>
and the second one into ajax call.test_2.html
test_2.php
Try Adding prevent default on submit function. It will halt the form submission and the Ajax will fire.
JSON.stringify(array) to pass array in JSON format.
Use preventDefault() because preventDefault() will stop HTML form from submitting and will allow $.ajax to submit form instead.
In your case you are not using preventDefault(), so ajax is not firing and form is submitting by HTML form action.
Also note I passed e inside callback function of addEventListener. use that to call preventDefault(). (You can use any name)
Inside PHP use,