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

20

96

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?

Aileenailene answered 9/9, 2014 at 11:54 Comment(12)
does it really have Object at the start?Chasitychasm
@DanielA.White In js page? Would you please give little hint?Aileenailene
Why don't you use $(this).serialize() to post your data?Mollee
@Teemu thats why i'm here to ask. I'm kinda new. Could you please show me a little example. I don't want you to write whole code.Aileenailene
@Teemu its string i know..even if i tried to change all data to string nothing happens. There is 10 various fields in my database. only one is assigned to 'bigint' other ones are 'varchar'. There is my Json array output image up there. Can you see anything up there?Aileenailene
hahaha don't yell at me i'm just a 28 years old little boy! Almost 30! :) now it becomes : JSON.stringify(postData) .. so my output has changed to '{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"[email protected]","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}'... and now i'm having TypeError: data is null (need another beer! and for your help!)Aileenailene
@leventkaya Maybe you should keep the beer for after work :PMollee
@FlorianGl hehe its not problem in our agency :) I guess TypeError is a hint that i'm looking for. Its trying to say that your bottle is null.. lets fill me up! ... but i can't see what is TypeError? any ideas?Aileenailene
@leventkaya Maybe it's a problem for your concentration. Btw. what does clear() do? If it removes the value from $_POST, it is empty here: $data = array('success' => 'Register Completed', 'postData' => $_POST);. Could be thats the problem.Mollee
@FlorianGl ok no more no more beer. clear does : 'function clear($i) { return mysql_real_escape_string($i);}' ..Aileenailene
@leventkaya just for testing purposes, try changing $data = array('success' => 'Register Completed', 'postData' => $_POST); to $data = array('success' => 'Register Completed');Mollee
@Teemu i know dude :) thx for ur support. i'm gonna find you again if i got stuck. thx againAileenailene
D
29

The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.

Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file

$("#register-form").submit(function (event) {

    var entrance = $(this).find('input[name="IsValid"]').val();
    var password = $(this).find('input[name="objPassword"]').val();
    var namesurname = $(this).find('input[name="objNameSurname"]').val();
    var email = $(this).find('input[name="objEmail"]').val();
    var gsm = $(this).find('input[name="objGsm"]').val();
    var adres = $(this).find('input[name="objAddress"]').val();
    var termsOk = $(this).find('input[name="objAcceptTerms"]').val();

    var formURL = $(this).attr("action");


    if (request) {
        request.abort(); // cancel if any process on pending
    }

    var postData = {
        "objAskGrant": entrance,
        "objPass": password,
        "objNameSurname": namesurname,
        "objEmail": email,
        "objGsm": parseInt(gsm),
        "objAdres": adres,
        "objTerms": termsOk
    };

    $.post(formURL,postData,function(data,status){
        console.log("Data: " + data + "\nStatus: " + status);
    });

    event.preventDefault();
});

PHP Edit:

 if (isset($_POST)) {

    $fValid = clear($_POST['objAskGrant']);
    $fTerms = clear($_POST['objTerms']);

    if ($fValid) {
        $fPass = clear($_POST['objPass']);
        $fNameSurname = clear($_POST['objNameSurname']);
        $fMail = clear($_POST['objEmail']);
        $fGsm = clear(int($_POST['objGsm']));
        $fAddress = clear($_POST['objAdres']);
        $UserIpAddress = "hidden";
        $UserCityLocation = "hidden";
        $UserCountry = "hidden";

        $DateTime = new DateTime();
        $result = $date->format('d-m-Y-H:i:s');
        $krr = explode('-', $result);
        $resultDateTime = implode("", $krr);

        $data = array('error' => 'Yükleme Sırasında Hata Oluştu');

        $kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
        $retval = mysql_query( $kayit, $conn ); // Update with you connection details
            if ($retval) {
                $data = array('success' => 'Register Completed', 'postData' => $_POST);
            }

        } // valid ends
    }echo json_encode($data);
Determinant answered 9/9, 2014 at 12:5 Comment(10)
let me check. also here is my database : linkAileenailene
where did you change on here? its like the same as old.. also i've tried doesn't work.Aileenailene
It was html markup being on a second line - this can cause problems if it's not on the same line as the opening " or 'Determinant
i tried. u chagenged my 'gsm' from varchar to int and i changed it to intval() but nothing happens. something still missing. it gives : TypeError: data is nullAileenailene
'console.log(data.success)' (JS file) It says : 'Uncaught TypeError: Cannot read property 'success' of null'Aileenailene
console.log(data) and see what it saysDeterminant
just 'null' :) trying to find in php page.Aileenailene
I've just updated the JS a bit, can you tell me what it returns?Determinant
here results : 'Data: {"success":"Register Completed","postData":{"objAskGrant":"Yes","objPass":"12312312","objNameSurname":"alskdjfl;asdkjf","objEmail":"[email protected]","objGsm":"3412341234","objAdres":"asdfasdf asdfasdfasf","objTerms":"CheckIsValid"}} Status: success'Aileenailene
offtopic : link this song is dedicated to you! thx manAileenailene
R
58

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.

Reinforce answered 14/1, 2015 at 9:11 Comment(0)
D
29

The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.

Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file

$("#register-form").submit(function (event) {

    var entrance = $(this).find('input[name="IsValid"]').val();
    var password = $(this).find('input[name="objPassword"]').val();
    var namesurname = $(this).find('input[name="objNameSurname"]').val();
    var email = $(this).find('input[name="objEmail"]').val();
    var gsm = $(this).find('input[name="objGsm"]').val();
    var adres = $(this).find('input[name="objAddress"]').val();
    var termsOk = $(this).find('input[name="objAcceptTerms"]').val();

    var formURL = $(this).attr("action");


    if (request) {
        request.abort(); // cancel if any process on pending
    }

    var postData = {
        "objAskGrant": entrance,
        "objPass": password,
        "objNameSurname": namesurname,
        "objEmail": email,
        "objGsm": parseInt(gsm),
        "objAdres": adres,
        "objTerms": termsOk
    };

    $.post(formURL,postData,function(data,status){
        console.log("Data: " + data + "\nStatus: " + status);
    });

    event.preventDefault();
});

PHP Edit:

 if (isset($_POST)) {

    $fValid = clear($_POST['objAskGrant']);
    $fTerms = clear($_POST['objTerms']);

    if ($fValid) {
        $fPass = clear($_POST['objPass']);
        $fNameSurname = clear($_POST['objNameSurname']);
        $fMail = clear($_POST['objEmail']);
        $fGsm = clear(int($_POST['objGsm']));
        $fAddress = clear($_POST['objAdres']);
        $UserIpAddress = "hidden";
        $UserCityLocation = "hidden";
        $UserCountry = "hidden";

        $DateTime = new DateTime();
        $result = $date->format('d-m-Y-H:i:s');
        $krr = explode('-', $result);
        $resultDateTime = implode("", $krr);

        $data = array('error' => 'Yükleme Sırasında Hata Oluştu');

        $kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
        $retval = mysql_query( $kayit, $conn ); // Update with you connection details
            if ($retval) {
                $data = array('success' => 'Register Completed', 'postData' => $_POST);
            }

        } // valid ends
    }echo json_encode($data);
Determinant answered 9/9, 2014 at 12:5 Comment(10)
let me check. also here is my database : linkAileenailene
where did you change on here? its like the same as old.. also i've tried doesn't work.Aileenailene
It was html markup being on a second line - this can cause problems if it's not on the same line as the opening " or 'Determinant
i tried. u chagenged my 'gsm' from varchar to int and i changed it to intval() but nothing happens. something still missing. it gives : TypeError: data is nullAileenailene
'console.log(data.success)' (JS file) It says : 'Uncaught TypeError: Cannot read property 'success' of null'Aileenailene
console.log(data) and see what it saysDeterminant
just 'null' :) trying to find in php page.Aileenailene
I've just updated the JS a bit, can you tell me what it returns?Determinant
here results : 'Data: {"success":"Register Completed","postData":{"objAskGrant":"Yes","objPass":"12312312","objNameSurname":"alskdjfl;asdkjf","objEmail":"[email protected]","objGsm":"3412341234","objAdres":"asdfasdf asdfasdfasf","objTerms":"CheckIsValid"}} Status: success'Aileenailene
offtopic : link this song is dedicated to you! thx manAileenailene
S
22

Remove

 dataType: 'json'

replacing it with

 dataType: 'text'
Stanton answered 9/3, 2016 at 20:35 Comment(0)
H
7

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.

Halcyon answered 26/12, 2014 at 15:51 Comment(0)
O
3

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}} 
Oleic answered 9/7, 2016 at 18:37 Comment(1)
Hey, It was really helpful, i were stuffing my mind for last 48 hours and it helped me, can you please explain why its behaving like that? Thank you. and +1 for the hint.Popup
K
3

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..

Kathline answered 18/8, 2019 at 12:6 Comment(1)
this was the case for me. If the path is wrong the response will not be valid for JSON formatting.Mich
O
3

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.

Outandout answered 31/8, 2020 at 6:55 Comment(0)
T
2

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.

Tallowy answered 21/7, 2016 at 13:37 Comment(0)
C
2

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");
            }

        });

});
Chaff answered 14/9, 2016 at 11:31 Comment(0)
N
1

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".

Neveda answered 16/2, 2017 at 1:45 Comment(0)
B
1

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);
Bilharziasis answered 25/9, 2017 at 14:27 Comment(0)
V
1

I was getting similar error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data".

It turns out I was sending data from the backend in JSON format already, so when it arrives on the front-end, I shouldn't use JSON.parse at all:

$.ajax({
    type: "get",
    url: 'https://localhost:8080/?id='+id,
    success: function (response) { // <- response is already JSON
        var data = $.parseJSON(response); // <- I removed this line
        modalShow(data); // <- modalShow(response) now works!
    }
});
Volunteer answered 30/9, 2022 at 9:0 Comment(0)
B
0

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) ;
},
Burgomaster answered 12/1, 2018 at 0:17 Comment(0)
C
0

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);
Cheerful answered 5/6, 2018 at 10:35 Comment(0)
R
0

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

Good luck!

Ruffo answered 12/5, 2020 at 20:49 Comment(0)
D
0

I had the same error in an AJAX call in an app with pagination and or in any case with a query string in the URL

since AJAX was posting to something like

var url = window.location.href + 'search.php';
...
...
fetch(url, {
        method: 'POST', 
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({search: text}),
      })

as soon in the browser URL was added some query string, the error "JSON.parse: unexpected character at line 1 column 1" was popping

the solution has been to simply clean the URL from any query string with

var url = window.location.href.split('?')[0] + 'search.php';

and issue got fixed

So, the error was not the formatting of the Json, instead it was a wrong URL for the POST

Donndonna answered 4/9, 2021 at 12:51 Comment(0)
P
0

@Prahlad is on to something here. I've been seeing this thing for years and it just became background noise to me.

Recently I was doing some brand new stuff and I realized I was seeing that in my console (FF 98.0 (64-bit)) on Mac (12.2.1 (21D62)) where the html is being served by a local NGNIX install (nginx/1.21.6)

Here is the html being served, in it's entirety:

<!doctype html>
<html lang="en">
<head>
</head>
<body>
   Some text
</body>
</html>

Now... I don't have a clue why it is happening, but I'm pretty sure it's not the code :-)

Pilar answered 13/3, 2022 at 22:28 Comment(0)
C
0

If you get this error from Laravel and Livewire when upload file, this solution fixed my issue hope help you too:

https://mcmap.net/q/219383/-notice-unknown-file-created-in-the-system-39-s-temporary-directory-in-unknown-on-line-0

Curricle answered 15/4, 2023 at 5:51 Comment(0)
B
0

For me it was because there was a call to .json() i.e. await response.json(). I couldn't find it because I was looking for JSON.parse.

Briggs answered 30/4, 2023 at 4:45 Comment(0)
A
0

I was getting that error when posting to a Shopify endpoint to create an account. While troubleshooting I checked the Network tab in Dev Tools and found the call. Then when I looked at the Response tab I discovered that it was returning the entire page in HTML. So then I tried an experiment. I switched .json() to .text() and that gave me a blob of HTML, which wasn't helpful for what I was doing, but helped me understand why the error was occurring.

  const formData = new FormData(form);
  const response = await fetch('/account', {
    method: 'POST',
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    },
    body: formData
  });

  const text = response.text();
  console.log('---REGISTER DATA', text);

  if (!response.ok) {
    throw new Error(response.status);
  }
Advisory answered 28/3 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.