0

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?

imagina
  • 65
  • 1
  • 6
  • `$.getJSON('test-call.php', function(response) { console.log(response); });` The next step is to look at console output and go from there. –  Mar 28 '18 at 20:35

1 Answers1

4

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>
Syscall
  • 19,327
  • 10
  • 37
  • 52
  • I find that I get a 404 in console however, if the url has a query string to enable it to look up its values in a database (as in `test-call.php?id=123`). Is it possible to alter the code to accommodate URLs with query strings? – imagina Mar 29 '18 at 10:25
  • Actually I'm not sure it is the presence of the query string in the URL that's causing the 404. It looks like it is the fact that test-call.php does a DB lookup. If I don't do the DB lookup in test-call.php, and just hard-code the output data, the AJAX call works. But if I do allow test-call.php to look up (whether or not I include the query string in the AJAX code), I get the 404. – imagina Mar 29 '18 at 10:30
  • Ah - sorry - it was neither. Sorry for the false alarm - it was an unrelated uncommented line in test-call.php for login purposes. Syscall's code works fine. – imagina Mar 29 '18 at 10:34