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

I've spend over 6 hours to find an exception or a special character to find in my code but I couldn't. I checked every similar messages in here.

I'm sending the form with magnific popup. First I'm using inline popup to open my form than I'm sending all inputs to main.js to validate.

So, I just need a third-eye.

I've got: index.html, register.php, main.js

Here's the code

FORM

JS/AJAX

PHP-register.php

Here goes the error messages

JSON Output json

Chrome Console:

chrome

Firefox console : firefox


What am i missing?

This question is related to javascript php jquery ajax json

The answer is


In some cases data was not encoded into JSON format, so you need to encode it first e.g

 json_encode($data);

Later you will use json Parse in your JS, like

JSON.parse(data);

May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.

//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);

When the result is success but you get the "<" character, it means that some PHP error is returned.

If you want to see all message, you could get the result as a success response getting by the following:

success: function(response){
     var out = "";
     for(var i = 0; i < response.length; i++) {
        out += response[i];
     }
     alert(out) ;
},

Even if your JSON is ok it could be DB charset (UTF8) problem. If your DB's charset/collation are UTF8 but PDO isn't set up properly (charset/workaround missing) some à / è / ò / ì / etc. in your DB could break your JSON encoding (still encoded but causing parsing issues). Check your connection string, it should be similar to one of these:

$pdo = new PDO('mysql:host=hostname;dbname=DBname;**charset=utf8**','username','password'); // PHP >= 5.3.6

$pdo = new PDO('mysql:host=hostname;dbname=DBname','username','password',**array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")**); // older versions

P.S. Outdated but still could be helpful for people who're stuck with "unexpected character".


For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.

e.g.

var d = "";
var json = JSON.parse(d);

or if you are using AngularJS

var d = "";
var json = angular.fromJson(d);

In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.

Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.


Remove

 dataType: 'json'

replacing it with

 dataType: 'text'

Are you sure you are not using a wrong path in the url field? - I was facing the same error, and the problem was solved after I checked the path, found it wrong and replaced it with the right one.

Make sure that the URL you are specifying is correct for the AJAX request and that the file exists.


Try using MYSQLI_ASSOC instead MYSQL_ASSOC... usually the problem is solved changing that

Good luck!


I have got same Error while fetch data from json filesee attached link

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

So, i check the path of the json file which isn't correct,

const search = document.getElementById("search");
const matchList = document.getElementById("match-list");

//search json data and filter
const searchStates = async searchText => {
    const res = await fetch('../state.json');
    const states = await res.json();
    console.log(states);
}

search.addEventListener('input', () => searchStates(search.value));

so that i changed the path of the file

const res = await fetch('./state.json');

& it gives me array back as a result. so, check your path & try changed it. It will work in my case. I hope that's works..


Changing the data type to text helped dataType: 'text'

I have check with JSONlint and my json format was proper. Still it was throwing error when I set dataType: 'json'

JSON Data: {"eventinvite":1,"groupcount":8,"totalMessagesUnread":0,"unreadmessages":{"378":0,"379":0,"380":0,"385":0,"390":0,"393":0,"413":0,"418":0}} 

I have the exact same issue and I've found something. I've commented the line :

dataType : 'json',

after that it was successful but... when I did console.log(data) it returned the main index.html.

That's why you have "Unexpected token <" error and it cannot parse.


Sending JSON data with NodeJS on AJAX call :

$.ajax({
    url: '/listClientsNames',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify({foo:'bar'})
}).done(function(response){
    console.log("response :: "+response[0].nom);
});

Be aware of removing white spaces.

app.post("/listClientsNames", function(req,res){

        var querySQL = "SELECT id, nom FROM clients";   
        var data = new Array();

        var execQuery = connection.query(querySQL, function(err, rows, fields){

            if(!err){
                for(var i=0; i<25; i++){
                    data.push({"nom":rows[i].nom});         
                }
                res.contentType('application/json');
                res.json(data); 
            }else{  
                console.log("[SQL005] - Une erreur est survenue");
            }

        });

});

JSON.parse() doesn't recognize That data as string. For example {objAskGrant:"Yes",objPass:"asdfasdf",objNameSurname:"asdfasdf adfasdf",objEmail:"[email protected]",objGsm:3241234123,objAdres:"asdfasdf",objTerms:"CheckIsValid"}

Which is like this: JSON.parse({objAskGrant:"Yes",objPass:"asdfasdf",objNameSurname:"asdfasdf adfasdf",objEmail:"[email protected]",objGsm:3241234123,objAdres:"asdfasdf",objTerms:"CheckIsValid"}); That will output SyntaxError: missing " ' " instead of "{" on line...

So correctly wrap all data like this: '{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"[email protected]","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}' Which works perfectly well for me.

And not like this: "{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"[email protected]","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}" Which give the present error you are experiencing.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?