1

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

2
  • 1
    did you put session_start() on top of the all pages ? Commented Apr 17, 2018 at 5:09
  • 1) ajax.php does not have any response body so data will always be empty. 2) You'd need to reload adopt.php in order for it to pick up any changes in $_SESSION Commented Apr 17, 2018 at 5:10

3 Answers 3

2

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"]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks for the answer, it's returning the object back now. :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.