-1

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.

After remove var dump i get this error: enter image description here

Rony Cohen
  • 87
  • 2
  • 14
  • 1
    `"As you can see, the JSON string is not properly formatted"` the above is not JSON, not even close – Professor Abronsius Jun 12 '23 at 12:59
  • 3
    If you are outputting JSON (or trying to) then `var_dump($tableName);` will introduce errors immediately – Professor Abronsius Jun 12 '23 at 13:00
  • @ProfessorAbronsius I know it's strange but this is what i get using console.log(response). Have you any idea why there is this error so: Uncaught SyntaxError: JSON.parse: unexpected character" error. – Rony Cohen Jun 12 '23 at 13:02
  • 2
    Despite the use of `mysqli_real_escape_string` your code is potentially vulnerable to SQL injection. Always use `prepared statements` when using data supplied by the user in your SQL – Professor Abronsius Jun 12 '23 at 13:02
  • Rony - remove the `var_dump` – Professor Abronsius Jun 12 '23 at 13:02
  • @ProfessorAbronsius see my edit after remove var_dump – Rony Cohen Jun 12 '23 at 13:06
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jun 12 '23 at 13:09
  • 2
    As part of the SQL injection - are you really passing the column names as POST variables? This is a very bad idea and can cause all sorts of problems. – Nigel Ren Jun 12 '23 at 13:12
  • JavaScript console is not the best place to trouble-shoot server-side JSON generation. Switch to "Network" tab to inspect the response of the end-point. You may also want to add the `JSON_THROW_ON_ERROR` flag to detect errors. – Álvaro González Jun 12 '23 at 13:19
  • I can still see `var_dump($tableName);` in your PHP above even after your edit. Essentially **any** character data that is output before the JSON (even a blank space) will cause an error – Professor Abronsius Jun 12 '23 at 13:21
  • @ÁlvaroGonzález Can you help understand where to insert it in my code, to view the json error – Rony Cohen Jun 12 '23 at 13:27
  • @ProfessorAbronsius I delete the var_dump but still error – Rony Cohen Jun 12 '23 at 13:27
  • You don't need to insert it anywhere. Your current browser is displaying it already, you only need to open the appropriate tab, which is not "Console" but "Network". – Álvaro González Jun 12 '23 at 13:35
  • @ÁlvaroGonzález on network dont see any error. – Rony Cohen Jun 12 '23 at 13:47
  • ProfessorAbronsius @ÁlvaroGonzález this is the json i get for example { "status": 200, "message": "Data Fetch Successfully by id", "data": { "0": "891", "train_id": "891", "1": "777", "name": "777", "2": "777", "type": "777", "3": "81", "capacity": "81" } } – Rony Cohen Jun 12 '23 at 14:11

1 Answers1

0

May be is because your response was empty, try to don't use the ajax for the moment and use your part of code in php field who you need to past this ajax request for see if is empty or not.

Marina
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 16 '23 at 13:36