Reputation: 217
Is it possible to pass two variables from PHP to AJAX and use them seperately for instance:
fetching this:
echo $row['route'] + $row['Distance'] ;
which I then can:
$.getJSON("DisplayIndividualMySQLi.php", function(data) {
// alert(route);
// alert(distance);
}
Upvotes: 1
Views: 100
Reputation: 8083
When you are grabbing data from php with getJSON, your response from php needs to be in json
http://php.net/manual/en/function.json-encode.php
// DB Query to set $row[ 'route' ] and $row[ 'Distance' ]
$sql = "SELECT route, Distance, UserID, RandomField, Etc FROM foo where bar = 'baz' LIMIT 1";
$row = $db->query( $sql )->fetch_assoc();
//...
$array = array(
'route' => $row[ 'route' ],
'distance' => $row[ 'Distance' ],
'UserID' => $row[ 'UserID' ]
);
// returns { "route": "foo", "Distance": "bar", "UserID": "User" }
echo json_encode( $array );
// Case is important on things in the data object!
$.getJSON( "DisplayIndividualMySQLi.php", function( data ) {
console.log( data ); // Object
console.log( data.route ); // shows php's $row[ 'route' ]
console.log( data.Distance ); // shows php's $row[ 'Distance' ]
} );
Upvotes: 6
Reputation: 572
You can put them together in an array, which you then json-encode() and echo.
$array = array(
"route" => $row['route'],
"distance" => $row['Distance'],
);
echo json_encode( $array);
or if you want to send the whole $row you can just :
echo json_encode( $row);
(But only send data that you need for good practice.)
Afterwards you can access the data as data.route, for instance :
console.log( data.route );
Upvotes: 2