0

I'm trying to use JQuery to send AJAX data from a web browser to a PHP script in a web server and then getting a response back from the server. The request is received and processed correctly by the PHP script, but there seems to be something in the server's response that JQuery can't parse. Using Firefox, I get the following error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

And using Chromium I get something like this:

SyntaxError: Unexpected token in JSON at position 0

I'm not sure if that's a blank space or some other character, as Chromium won't let me copy the alert text.

Anyway, here's the PHP script that resides in the server, processes the AJAX request and generates the response. I previously used json_encode() to return dynamically generated data, but right now I'm using a static string just to try to make it work:

<?php
echo '[{"id":1,"label":"sinetiqueta","value":"nada","url":"nadicaDeUrl"}]';
?>

And here's my JQuery AJAX code:

$.ajax({
    url: 'www.siteurl.com/server_script.php',
    method: 'GET',
    cache: false,
    contentType: "application/json; charset=utf-8",
    data: request,
    dataType: 'json',
    dataFilter: function  ( recieved_data, data_type ) {
        //I added this function just to check the JSON data before it gets parsed by JQuery
        alert('DATAFILTER --- recieved_data: ' + recieved_data + ' * data_type: ' + data_type);
        var filtered_data = recieved_data;
        return (filtered_data);
    },
    success: function (json) {
        alert('SUCCESS --- json: ' + json);
        response($.map(json, function () {
            return json;
        }));
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('error - ' + textStatus + ': ' + errorThrown + ' * Server Response:_' + XMLHttpRequest.responseText + '_')
    }
});

So the PHP script gets JQuery's message without a problem, returns a static string of (as far as I can tell) properly formed JSON that gets back to the browser without a problem (that alert command in the dataFilter function shows the same string that PHP sends back) but JQuery can't parse it.

The funny thing is: If I insert that very same static string directly in the dataFilter function instead of passing it from the PHP script, JQuery parses it properly and everything else works without a hitch!

    dataFilter: function  ( recieved_data, data_type ) {
        alert('DATAFILTER --- recieved_data: ' + recieved_data + ' * data_type: ' + data_type);
        /*var filtered_data = recieved_data;*/
        //instead of using the data I got from PHP, I use a string literal value
        var filtered_data = '[{"id":1,"label":"sinetiqueta","value":"nada","url":"nadicaDeUrl"}]';
        return (filtered_data);
    },

This works, but it obviously doesn't suit my needs, as I need to use the JSON data that gets sent back from the server. Right now, I'm using the very same JSON string, only JQuery can't parse when it gets it from PHP, even when it seems to be receive it complete and properly encoded, as far as I can tell.

I'm at a loss to figure out what may be happening with the data that I get from PHP. When displayed with the alert command in the dataFilter() function, it looks perfectly ok! What am I missing here? Any help will be greatly appreciated. Thanks in advance!

4
  • Either try putting json_encode in php script and adjust the http header content type to json or use JSON.parse(received_data) on the data fetched in ajax Commented May 21, 2016 at 19:13
  • 2
    Never "manually produce" JSON. Always encode an actual data strucutre (in PHP use json_encode). Your real issue will probably be found when you look for extra whitespace before and after opening and closing PHP tags in all involved PHP files. Also look into whether ir not your editor is putting inserting a byte order mark (BOM) for UTF-8 files Commented May 21, 2016 at 19:22
  • In browser dev tools network inspect actual response from server. Copy 100% of it to a json validator and see what happens. Commented May 21, 2016 at 19:46
  • @JAAulde: Thanks a lot! That was it. I had already checked that all PHP tags were left unclosed, to avoid potential whitespace problems, but there was a harmless looking little file that was included on the PHP side, that some text editor had added the byte order mark to. It took me quite a while to notice that, and I probably wouldn't have noticed without your tip. Thanks again! Commented May 23, 2016 at 20:16

1 Answer 1

1

Thanks to user JAAulde, I found the cause of my problems. The server side PHP script returned properly formatted JSON data, and checking it with the browser's network inspector and in the JQuery script after reception, I couldn't see any extraneous characters that could stop the parser from processing it.

The cause of my problems was a little configuration file I included in the PHP script, that some text editor had codified as UTF8 with BOM (byte order mark), the mere inclusion of which, apparently produces some kind of undisplayable output that gets added to the beginning of the data and messes JSON parsing in the client script. Be careful with the BOM in your UTF-8 encoded files when you need to send data for another script to process, kids!

Many thanks to users Nitin and charlietfl for their helpful and reasonable answers, too!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.