I'm running into an issue where the JSON returned from a PHP query is not valid and I'm not really sure why; I'm still learning. When the datatype
is excluded the below code returns:
{"Customer_ID":"0", "FirstName":"John", "LastName":"Smith"}
{"Customer_ID":"1", "FirstName":"Jane", "LastName":"Smith"}
otherwise it returns:
SyntaxError: "JSON.parse: unexpected non-whitespace character after ..."
I thought this might be because the record is not being returned in a single JSON response, but I can't see that being the issue as the concurrent responses are JSON. Any ideas? Any suggests? Feel free to point out the semantic issues.
HTML:
getRecord("*", "customer", "");
JavaScript:
function getRecord(field, table, condition) {
var request = $.ajax({
url: "./handler.php",
method: "GET",
dataType: "JSON",
cache: "false",
data: {
action: "SELECT",
field: `${field}`,
table: `${table}`,
condition: `${condition}`,
},
});
request.done(function(data, status, xhr) {
console.log(data, status, xhr);
});
request.fail(function(xhr, status, error) {
console.log(xhr, status, error);
});
};
PHP:
<?php
# IMPORT SETTINGS.
include "settings.php";
# FUNCTION DISPATCHER.
switch($_REQUEST["action"]) {
case "SELECT":
getRecord($conn);
break;
default:
printf('Connection Error: Access Denied.');
mysqli_close($conn);
}
# LIST OF COLUMNS THAT WE NEED.
function getRecord($conn) {
$table = $_REQUEST["table"];
$field = $_REQUEST["field"];
$condition = $_REQUEST["condition"];
if (!empty($condition)) {
$query = "SELECT $field FROM $table WHERE $condition";
} else {
$query = "SELECT $field FROM $table";
}
if ($result = mysqli_query($conn, $query)) {
while ($record = mysqli_fetch_assoc($result)) {
echo json_encode($record);
}
}
# CLOSE THE CONNECTION.
mysqli_close($conn);
}
?>