Ajax Post to PHP returning empty array

I need to pass a json object from JS to PHP, and it will pass, but the result is an empty array.

Ajax request in 'adopt.php':

var info = JSON.stringify(filteredArray);
$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: {'info': info},
    success: function(data){
        console.log(data);
    }
});

ajax.php code:

if(isset($_POST['info'])){
    $_SESSION['array'] = $_POST['info'];
}

back in adopt.php, later:

if(isset($_SESSION['array'])){
    $arr = $_SESSION['array'];
    echo "console.log('information: ' + $arr);";
}

in both of the console.logs, it returns an empty object. Does anybody know what could be causing this? (i've tried just passing the json without stringifying it, but it throws a jquery error whenever i do this.)

3 answers

  • answered 2018-04-17 05:05 Aman Kumar

    Try below code i think you miss return ajax response

    adopt.php

    <script>
    var info = JSON.stringify(filteredArray);
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {info: info},
        success: function(data){
            console.log(data);
        }
    });
    </script>
    

    ajax.php

    if (isset($_POST['info'])) {
        $_SESSION['array'] = $_POST['info'];
        echo json_encode(["result" => "success"]);
    }
    

  • answered 2018-04-17 05:05 akhil

    Your ajax.php is not returning any data.To get data at the time of success you need to echo the data you want to display on success of your ajax.

  • answered 2018-04-17 05:05 Annapurna

    To get the response data from PHP, you need to echo your data to return it to the browser.

    In your ajax.php:

    if (isset($_POST['info'])) {
        $_SESSION['array'] = $_POST['info'];
        echo json_encode(['result' => $_SESSION['array']]);
    }