ceretello
ceretello

Reputation: 13

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.)

Upvotes: 1

Views: 1537

Answers (3)

Annapurna
Annapurna

Reputation: 549

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']]);
}

Upvotes: 1

Aman Kumar
Aman Kumar

Reputation: 4547

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"]);
}

Upvotes: 2

akhil
akhil

Reputation: 1

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.

Upvotes: 0

Related Questions