Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

php - SyntaxError: JSON.parse?

So i'm making a simple web application to test out Ajax and for some reason i'm getting JSON.parse error although i'm returning my results as JSON using json_encode($results). The application lets me pick a client and it pulls out that client's orders

JS file :


function getOrders(clientId) {
    $.ajax(
            {
            type: 'POST',
            url: "AjaxRequests.php",
            data : {
                action: 'showOrders',
                clientId: clientId
            },
            dataType : 'json',
            success: function(results){
                alert(results);
            },
            error: function(request, status, error){
                console.log(clientId);
                console.log(request.responseText);
                console.log('error : ' + error);
                console.log('status' + status);
            },
            
            }
    )
};

AjaxRequests.php file

<?php 
header('Content-Type: application/json; charset=UTF-8');
require_once './GestionClients.php';

if (isset($_POST['action'])) {
    if ($_POST['action'] == 'showOrders') {
        $clientId = $_POST['clientId'];
        $gc = new GestionClients();
        $results = $gc->getCmdsByClient($clientId);
        echo json_encode($results);
    }
}

?>

and this is the results i get in the console after i pick a client (first client in this example with an ID = 1 in the DB) from the selection list:

1 script.js:16:25
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}] script.js:17:25
error : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data script.js:18:25
statusparsererror

I tried putting that JSON result on an online JSON parser and it looks just fine. Thank you for your time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I so often advise, this problem could have been avoided, or at least quickly identified, by breaking the problem down: you were trying to debug the JS, but that wasn't the part that was broken.

In this case, you have two key pieces:

  1. A PHP script that, when requested with the right parameters, outputs something. You can open this in your browser, and see it for yourself.
  2. Some JS code which requests that PHP script, and parses its content as JSON. You can test this with a PHP script that just echoes {"hello": "world"}, or even a text file uploaded to your server.

Once you know that the JS code works if the JSON is valid, you can basically ignore #2, and look for problems in #1.

If you open the PHP script you wrote in a browser, it will show:

Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]

Now, we know that the JS is going to try to parse this as JSON, so we can do a quick test in our browser's console:

JSON.parse('Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');

We get a syntax error! Well, of course we do: that "Connection successfull!" wasn't supposed to be part of the JSON.

So we dig into the PHP code, work out where that's coming from, and stop it happening. Now we run the PHP again, and it looks like this:

[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]

Now we can do our JS test again:

JSON.parse('[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');

Now the error's gone away, and it gives us an array. While we're here, we can look at the structure of the array in the console and make sure it looks right.

Only now do we go back and run the original AJAX call, and see if it's all working. If it's not, we look for other steps we can break out, and repeat the process.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...