skip to Main Content

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


  1. You are making two requests:

    1. $.post('page2.php', ... sends an AJAX POST request to page2.php with the POST data you specified. You can see that request by checking the Network Tab in your Browsers Developer Tools.
    2. 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.
    Login or Signup to reply.
  2. You can save your array at the page2.php

    $_SESSION['my-array'] = $_POST['categoriesActives'];
    

    Next redirect user like you do, but to the page3.php

    window.location.assign('https://dom.fr/page3/');
    

    And at the page3.php you get this array:

     $array = [];
    
     if (isset($_SESSION['my-array'])) {
        $array = $_SESSION['my-array'];
        unset($_SESSION['my-array']);
     } else {
        $array = ['a', 'z', 'e', 'r'];
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search