I am trying to send the content of a JavaScript array to a different page using $.post, but it doesn’t work – the coreresponding $_POST is not set…
Can someone explain me what’s wrong ?
Here is the js code, on page 1:
<script type="text/javascript">
var i = sessionStorage.length;
var categoriesTab = [];
for (let j = 0; j < i; j++) {
if (sessionStorage.getItem(sessionStorage.key(j)) == 'active') {
categoriesTab.push(sessionStorage.key(j));
}
}
const liste = document.getElementById('liste');
liste.addEventListener('click', function (event){
event.preventDefault();
if (window.location.href == 'https://dom.fr/page1/'){
$.post(
'page2.php',
{
categoriesActives : categoriesTab
}
)
}
window.location.assign('https://dom.fr/page2/');
});
</script>
The categoriesTab variable is set and everything seems to work.
But when I get to page 2, $_POST is empty… :
<?php
$array = [];
if (isset($_POST['categoriesActives'])) {
$array = $_POST['categoriesActives'];
} else {
$array = ['a', 'z', 'e', 'r'];
}
?>```
2
Answers
You are making two requests:
$.post('page2.php', ...
sends an AJAX POST request topage2.php
with the POST data you specified. You can see that request by checking the Network Tab in your Browsers Developer Tools.window.location.assign('https://dom.fr/page2/');
redirects the browser to the specified URL using a normal GET request. In that case $_POST is empty because it is another request.You can save your array at the page2.php
Next redirect user like you do, but to the page3.php
And at the page3.php you get this array: