Try To Return JSON Data Generated With SQL Statement From PHP Script To JS Webpage But Get Null Instead
I want to return JSON data from a resulted SQL statement in a PHP script upon pressing Submit button, but I receive null instead. I'll be using the returned JSON to filter-show mar
Solution 1:
You can't return the result object of a mysql_query
call directly. You first have to parse it with functions like mysql_fetch_array
or alike (PHP docu).
...
$result = mysql_query($query);
if ( $result === false ) {
die("Can\'t do that: " . mysql_error());
}
$retVal = array();
while( $row = mysql_fetch_array( $result ) ) {
$retVal[] = $row;
}
...
echo json_encode( $retVal );
EDIT
According to the jQuery spec for getJSON
(link), the data is sent using GET parameters and not using POST. So you would have to change all the $_POST
appearances in your PHP code to either $_GET
or $_REQUEST
.
Besides this, you should return some error messages if your variables are not set. Right now (according to your code) just an empty document is returned.
Solution 2:
Before the echo you should declare the returned content type:
header('Content-Type: application/json');
If you want to check for the receival of the data you can use:
$.ajax({
url: url,
data: myData,
success: function(json) {},
error: function(json) {} // this should allow you to check if data is received (but since the content type is set to text/html and $.getJSON expectr application/json it won't be a success)
});
Post a Comment for "Try To Return JSON Data Generated With SQL Statement From PHP Script To JS Webpage But Get Null Instead"