imagina
imagina

Reputation: 65

TypeError when trying to call JSON data via AJAX

I'm trying to pass some JSON data from a PHP page to javascript, but it's not working.

The PHP page test-call.php outputs some minimal test data like so:

<?php
$username = 'MyValue';
$data = array('retid' => $username);
echo json_encode($data);
?>

The calling page loads jquery <script src="http://code.jquery.com/jquery-1.8.0.js"></script> in the <head> and has javascript as recommended elsewhere like this:

<script>
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
    success: function(response) {
        var retid = response.data.retid;
        console.log(retid);
    },
});
</script>

However, running the javascript results in an error described by console as"

TypeError: undefined is not an object (evaluating 'response.data.retid')

What is wrong here?

Upvotes: 0

Views: 54

Answers (1)

Syscall
Syscall

Reputation: 19780

response is the data, so response.data is undefined. You can access to your data using response.retid:

<script>
$.ajax({
    type: 'POST',
    url: 'test-call.php',
    dataType: 'json',
    success: function(response) {
        var retid = response.retid;
        console.log(retid);
    },
});
</script>

Upvotes: 4

Related Questions