I'm currently facing an issue with JSON encoding in PHP, specifically when using the json_encode function. Whenever I try to parse the JSON data in my JavaScript code, I encounter an "Uncaught SyntaxError: JSON.parse: unexpected character" error.
Here's a brief overview of my code structure:
In my PHP file, code.php, I have a conditional block that checks if the table_name parameter is present either in the POST or GET request. Based on that, I set the $tableName variable accordingly. I then proceed to perform various database operations, such as inserting, updating, or deleting records from the specified table.
To handle the response from the server, I'm using an AJAX call in my JavaScript code. Upon receiving a successful response, I attempt to parse the JSON data using jQuery.parseJSON. However, this is where I encounter the unexpected character error.
After some debugging, I discovered that the issue lies in the JSON formatting generated by the json_encode function in PHP. When I examine the response from the server, I get the following output:
<pre class='xdebug-var-dump' dir='ltr'>
C:\wamp64\www\shira\new\code.php:11:string 'Trains' (length=6)
</pre>
As you can see, the JSON string is not properly formatted, which causes the parsing error in JavaScript.
I would greatly appreciate any insights or suggestions on how to resolve this issue. How can I ensure that the JSON encoding in PHP produces a correctly formatted JSON string that can be parsed without errors in my JavaScript code?
Thank you in advance for your assistance!
$(document).on('click', '.editTrainBtn', function () {
let tableName = "Trains";
var train_id = $(this).val();
$.ajax({
type: "GET",
url: "../code.php?train_id=" + train_id + "&table_name=" + tableName,
success: function (response) {
console.log(response);
var res = jQuery.parseJSON(response);
if (res.status == 404) {
alert(res.message);
} else if (res.status == 200) {
$('#train_id').val(res.data.train_id);
$('#name').val(res.data.name);
$('#type').val(res.data.type);
$('#capacity').val(res.data.capacity);
$('#trainEditModal').modal('show');
}
}
});
code.php
<?php
require 'database-log.php';
if (isset($_POST['table_name'])) {
$tableName = $_POST['table_name'];
} elseif (isset($_GET['table_name'])) {
$tableName = $_GET['table_name'];
} else {
// Handle the case when $tableName is not present in POST or GET
$tableName = ""; // Set a default value or handle the error condition
}
if (isset($_POST['save_' . $tableName])) {
$fields = '';
$values = '';
foreach ($_POST as $field => $value) {
if ($field !== 'save_' . $tableName) {
$escaped_field = mysqli_real_escape_string($con, $field);
$escaped_value = mysqli_real_escape_string($con, $value);
$fields .= "$escaped_field, ";
$values .= "'$escaped_value', ";
}
}
$fields = rtrim($fields, ', ');
$values = rtrim($values, ', ');
if ($fields == '' || $values == '') {
$res = [
'status' => 422,
'message' => 'All fields are mandatory'
];
echo json_encode($res);
return;
}
$query = "INSERT INTO $tableName ($fields) VALUES ($values)";
$query_run = mysqli_query($con, $query);
if ($query_run) {
$res = [
'status' => 200,
'message' => ucfirst($tableName) . ' Created Successfully'
];
echo json_encode($res);
return;
} else {
$res = [
'status' => 500,
'message' => ucfirst($tableName) . ' Not Created'
];
echo json_encode($res);
return;
}
}
if (isset($_POST['update_' . $tableName])) {
$idFieldName = $tableName . '_id';
$idValue = mysqli_real_escape_string($con, $_POST[$idFieldName]);
// Extract fields and their corresponding values dynamically
$update_fields = '';
foreach ($_POST as $field => $value) {
if ($field !== 'update_' . $tableName && $field !== $idFieldName) {
$escaped_field = mysqli_real_escape_string($con, $field);
$escaped_value = mysqli_real_escape_string($con, $value);
$update_fields .= "$escaped_field='$escaped_value', ";
}
}
$update_fields = rtrim($update_fields, ', ');
if ($update_fields == '') {
$res = [
'status' => 422,
'message' => 'All fields are mandatory'
];
echo json_encode($res);
return;
}
$query = "UPDATE $tableName SET $update_fields WHERE $idFieldName='$idValue'";
$query_run = mysqli_query($con, $query);
if ($query_run) {
$res = [
'status' => 200,
'message' => ucfirst($tableName) . ' Updated Successfully'
];
echo json_encode($res);
return;
} else {
$res = [
'status' => 500,
'message' => ucfirst($tableName) . ' Not Updated'
];
echo json_encode($res);
return;
}
}
if (isset($_POST['delete_' . $tableName])) {
$idFieldName = $tableName . '_id';
$idValue = mysqli_real_escape_string($con, $_POST[$idFieldName]);
$query = "DELETE FROM $tableName WHERE $idFieldName='$idValue'";
$query_run = mysqli_query($con, $query);
if ($query_run) {
$res = [
'status' => 200,
'message' => ucfirst($tableName) . ' Deleted Successfully'
];
echo json_encode($res);
return;
} else {
$res = [
'status' => 500,
'message' => ucfirst($tableName) . ' Not Deleted'
];
echo json_encode($res);
return;
}
}
if (isset($_GET[$tableName . '_id'])) {
$idFieldName = $tableName . '_id';
$idValue = mysqli_real_escape_string($con, $_GET[$tableName . '_id']);
$query = "SELECT * FROM $tableName WHERE $idFieldName='$idValue'";
$query_run = mysqli_query($con, $query);
if (mysqli_num_rows($query_run) == 1) {
$data = mysqli_fetch_array($query_run);
$res = [
'status' => 200,
'message' => 'Data Fetch Successfully by id',
'data' => $data
];
echo json_encode($res);
return;
} else {
$res = [
'status' => 404,
'message' => 'Data Id Not Found'
];
echo json_encode($res);
return;
}
}
?>
I get the same error of formatting for other crud operations, but I think the solution has to be the same for all.