简体   繁体   中英

PHP json_encode to AJAX, undefined

I'm new at AJAX and I am just trying to display the database results from PHP to HTML via AJAX. I'm getting "undefined" on console log when I load the page. HTML, PHP and the JS files are separated from each other.

Here's my JS Code:

$(document).ready(function(){

$.ajax({

    type: "GET",
    url:  "xaja.php",
    dataType: "json",
    contentType: "application/json; charset=utf-8",

    success: function(data){
        console.log(""+data.name);
    },
    error: function(e){
        alert("Error:\n"+e);
    }

});

});

Here's my PHP Code:

<?php

$json = array(

'username' => '',
'name' => '',
'loc' => ''

);


$sql = "Select * from tbluser";
$query = mysql_query($sql, $conn);
$result = mysql_fetch_assoc($query);

do{
    $json['username'] = $result['username'];
    $json['name'] = $result['name'];
    $json['loc'] = $result['location'];
    echo json_encode($json);
    $result = mysql_fetch_assoc($query);

}
while($result);

?>

Am I missing something here? Thanks in advance!

You are outputting multiple json strings. In order for your respond to be parsed it needs to be a single string. Try this instead:

$results = array();
do{
    $json['username'] = $result['username'];
    $json['name'] = $result['name'];
    $json['loc'] = $result['location'];
    $results[] = $json;
    $result = mysql_fetch_assoc($query);
}
while($result);
echo json_encode($results);

why not traditional way?

$sql = "Select * from tbluser";
$query = mysql_query($sql, $conn);

if ($result = mysql_fetch_assoc($query) ) {
    $json['username'] = $result['username'];
    $json['name'] = $result['name'];
    $json['loc'] = $result['location'];
    echo json_encode($json);
}

or if you need array of array:

$json = array();
$sql = "Select * from tbluser";
$query = mysql_query($sql, $conn);

while ($result = mysql_fetch_assoc($query) ) {
    $json[] = array($result['username'], $result['name'], $result['location']);
}
echo json_encode($json);

When returning JSON it should be a single structure, instead of outputting an array for each row, you should rather be building the array and outputting it once.

$json = array();
do {
    $json[]=$result;
    $result = mysql_fetch_assoc($query);
} while($result);
echo json_encode($json);

Which shows each row as a named structure ( [{username:"",name:"",location:""},{}..] )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM