I'm completely new to ajax so I'm not sure if I'm doing it correctly. I'm trying to pass an Javascript array to a PHP file. And if succesfully open the PHP file and display the array. The error I'm getting after opening the file is:
undefined $productList
Meanwhile if I inspect and look into the network tab the ajax is sent successfully and the response is also fine (I get to see the contents of the array), but when I try to open the file it throws me errors. So my question is how do I open a file where I send my data to with ajax?
Array:
array(6) { ["name"]=> string(28) "Inuyasha by rumiko takahashi" ["image"]=> string(35) "https://via.placeholder.com/195x280" ["id"]=> string(1) "5" ["count"]=> string(1) "1" ["price"]=> string(2) "12" ["basePrice"]=> string(2) "12" }
The ajax:
function passArray(){
$.ajax({
type: "POST",
url: "assets/js/test.php",
data: {productsInCart:productsInCart},
error: function(){
alert('something went wrong..');
}
});
//window.open("assets/js/test.php", "_self"); //how to open the file where the data is sent?
}
The PHP code:
if($_POST){
$productlist = $_POST;
}else{
$productlist = "";
echo "doesnt work ";
die();
}
//var_dump($productlist);
foreach($productlist as $number){
foreach ($number as $cat => $prop) {
echo $cat;
echo $prop;
}
}
$html .= "</table>";
CodePudding user response:
You are making two different requests to the same URL.
- With
$.ajax
you are making a POST request. - With
window.open
you are making a GET request.
The PHP program will run independently for each request. The data you are posting in the first request will not be available in the second request.
If you want to display a page you get as the result of POSTing some data then use:
<form action="..." method="post" target="_self">
Don't use Ajax (which is for making an HTTP request without leaving the current page — generally you would take the data in the response to the Ajax request and use DOM manipulation to add it to the current page).