I am trying to create a demo to get data from a PHP script that runs a SQL query, takes the associated array and json_encodes's it and returns it to the JQuery ajax caller in the calling php file. For some reason it never arrives (check with Firebug). But if I manually create a 2D array, json_encode it, it works fine. I am completely stumped why my array never makes it from SQL but it does if I just hand type it. I have diffed the resulting strings and they are exactly the same.
Code:
...snip...
$.ajax({
type: "GET",
url: "getclients.php",
data: { username: $('#staff_list').val() },
//contentType: "application/json",
dataType: 'json',
success: function(results) {
console.log("results");
},
fail: function() {
console.log("fail!!");
},
error: function(r, e, m) {
console.log("error");
//console.dir(r);
console.log(e + ', ' + m);
}
})
.done(function(data) {
console.log("done");
//console.log(data);
});
console.log("done with change detection...");
...snip...
PHP File:
<?php
header('Content-Type: application/json');
error_reporting(0); // prevents a notice from breaking ajax
//session_start();
$username = $_GET['username'];
$json = array();
$test = array(
array("id"=>4,"first_name"=>"Miles","last_name"=>"O'Brian"),
array("id"=>5,"first_name"=>"Jean Luc","last_name"=>"Picard"),
array("id"=>6,"first_name"=>"Reginald","last_name"=>"Barclay")
);
$mysqli = new mysqli('mydomain', 'myuser', 'mypassword', 'mydb');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT `id`, `first_name`, `last_name` FROM client WHERE provider_username = ?")) {
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$json[] = $row;
}
$result->close();
}
$mysqli->close();
echo json_encode($json);
echo json_encode($test);// this works
?>
Any help with this would be appreciated. I am new to PHP but not to programming so I tried everything I can think of (including the manual and Google) and am just completely stumped.
I figured out my problem. The line in the Ajax where I set the data:
data: { username: $('#staff_list').val() }
is causing the problem. For some reason it is getting an array, making the line
data: { username: $('#staff_list').val()[0] }
fixes the problem.
Can you please post your result set here which is return by the satement.
$result->fetch_assoc().
Please check your php version. Because the adding array element by using shorten method as you have used in your code "$json[] = $row;" is available in PHP 5.4. Look document for more information.
Second option if it is not available in your PHP version then you can achieve it as: array_push($json,$row); instead of $json[] = $row;
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.