SyntaxError: Unexpected '' on line 1 on validator JSONLINT - javascript

I come asking because I can't find any more trail for my problem. Hope someone could help me :)
Since several week, all in a sudden, my json got a weird unreadable character, provoking ajax request to raise an error instead of success state.
My code didn't change. I tried more tips like a simple boolean as return in the json. But nothing can help.
I lighten the code in order to avoid possible wrong character data.
I get an SyntaxError: Unexpected '' on line 1 when i try to validate on jsonlint he detects the wrong character
my code server side in php is the following :
$resultat = array();
$resultat['Success'] = true;
echo json_encode($resultat);
and my js ajax request :
var param = [{ name: "tbActionToDo", value: "InitialiseMailbox" }];
$.ajax({
type: "POST",
url: "actions/DatasourceEmail.php",
data: param,
dataType: "json",
dataFilter: function(data, type){
return data;
},
error: function(xhj, statut, thrown){
Notify("Danger", xhj.responseText);
},
success: function(result){
// do something
}
});
Thanks for your time and help !!

Related

Uncaught SyntaxError: Unexpected token in JSON at position 0

With some help, I have managed to make a form that validates and confirms user password before adding the user to the database. I have encountered some problem as the data of the user is not sent and giving me the following error :
Uncaught SyntaxError: Unexpected token in JSON at position 0 at JSON.parse () at Object.success (confirm3.php:29)
at i (jquery.min.js:2) at at A (jquery.min.js:4) at
XMLHttpRequest. (jquery.min.js:4)
The error
at Object.success (confirm3.php:29)
is referring to this following line
var data = JSON && JSON.parse(response) || $.parseJSON(response);
The POST variable
$UserNm=$_POST["UserNm"];
$UserId=$_POST["UserId"];
$UserPwd=$_POST["UserPwd"];
To make things clear, the data that should be returned is $ReturnMessage which is retrieved from stored procedure. $ReturnMessage will display the status of the operation for both successful and fail operation.
An example of $ReturnMessage :
"USER ID EXIST. (011 CODE)."
"USER ID MINT20 ADDED."
POST method is used : if(isset($_POST['Submit'])) {
$ReturnMessage :
if(isset($ReturnStatus) && $ReturnStatus==1) {
$ReturnMessage=odbc_result($stmt,'ReturnMessage');
}
}
$ReturnMessage = utf8_encode ($ReturnMessage);
echo json_encode($ReturnMessage);
}
Script :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#myForm").on("submit", function(e) {
e.preventDefault();
var password = $("#UserPwd").val();
var confirmPassword = $("#ConfirmPassword").val();
console.log(password,confirmPassword)
if ($.trim(password) === password &&
password !== "" &&
password === confirmPassword) {
$.ajax({
url: "confirm3.php",
method: "POST",
data: { Submit: "true" },
success: function(response) {
var data = JSON && JSON.parse(response) || $.parseJSON(response);
alert(data);
}
});
} else {
alert("Please Enter Password Correctly");
}
});
});
<script>
I'm kind of confuse. Please guide me. Thank you.
Have you set your content-type in your php?
header('Content-Type: application/json');
Also you don't need to put "true" in quote marks, when the json gets to your php script, once you run json_decode, php will recognise it as a boolean.
First of all, jQuery can decode JSON automatically for you (and it will make its best to guess). Trying to do it manually only makes your code more verbose and error-prone. However, you don't give it any hint. Nothing in the code you've shared gives any clue about your intention to use jQuery.
All the phases where you can do so, in chronological order:
Report data type from web server. If you happen to be using Apache:
<Files "confirm3.php">
ForceType application/json
</Files>
Report data type from PHP:
header('Content-Type: application/json');
Tell jQuery that you expect JSON:
url: "confirm3.php",
method: "POST",
dataType: "json",
data: { Submit: "true" },
success: function(response) {
console.log(data); // Already decoded (don't use alert to debug!)
}
You can certainly omit almost any step, but not all.
Secondly, if you get a JSON parse error the very first you need to check is whether the response is valid JSON. The most straightforward way to see it is using the browser developer tools, more specifically the "Network" pane.
Use this in my case there was some null bytes so this i figured out and it fixed my issues.
var data3 = data.substring(data.lastIndexOf("{")+1,data.lastIndexOf("}"));
count = $.parseJSON("{"+data3+"}");
alert( count.firstname ); // firstname is the key so you can use anything to test it.

Status 200 OK, same domain, valid JSON data and no response (Ajax)

Here's my ajax call:
$.ajax({
url : hostGlobal + "site/modulos/prefeitura/acoes-jquery.php",
type: "POST",
dataType : "JSON",
data: {
acao: "filtrarCidades",
estado_id: $(".estados:chosen").val()
},
success: function(json) {
console.log("worked");
$(".cidades").html('');
var options = "<option value=\"\"></option>";
$.each(json, function(key, value) {
options += '<option value="' + key + '">' + value + '</option>';
});
$(".cidades").html(options);
if (!filterThroughCEP) {
$(".cidades").trigger("chosen:updated");
}
},
error: function(e) {
console.log(e.responseText);
}
});
Here's the php action:
if ($acao == 'filtrarCidades') {
$estado_id = $_POST['estado_id'];
$cidade->where = "estado_id = '".$_POST['estado_id']."'";
$cidade->LoadFromDB();
for ($c=0; $c<count($cidade->itens); $c++) {
$cidades[$cidade->itens[$c]->id] = $cidade->itens[$c]->nome;
}
echo json_encode($cidades);
die();
}
json_encode($cidades) is valid json data (UTF8), here's one example using debug:
{"1778":"Bras\u00edlia"}
This {"1778":"Bras\u00edlia"} goes as e.responseText (Error), even with Status OK, and the URL is on the same domain (No need for JSONP). I have no idea why I can't reach success.
EDIT: I've set the contentType:
contentType: "application/json",
And the call still can't "reach" success. Here's the third error argument:
SyntaxError: Unexpected token
at parse (native)
at ajaxConvert (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7608:19)
at done (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7363:15)
at XMLHttpRequest.<anonymous> (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7835:9)
It is indeed related to unicode characters inside the strings that come from the database.
EDIT2: I wrote the whole thing again, and now it's clearer:
function getCitiesByState() {
$.ajax({
url : hostGlobal + "site/estrutura/ajax.php",
type: "POST",
dataType : "text",
data: {
action: "getCitiesByState",
state_id: $(".estados option:selected").val()
},
success: function(json, textStatus, jqXHR) {
console.log($.parseJSON(json));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
PHP:
if ($_POST["action"] == "getCitiesByState") {
$cities = getResults("SELECT * FROM tbl_cidades WHERE estado_id = ".$_POST["state_id"]);
echo json_encode($cities, JSON_UNESCAPED_UNICODE);
die();
}
Output:
[{"id":"1778","estado_id":"7","nome":"Brasília","cep":"","loc_no_abrev":"Brasília"}]
Error:
Uncaught SyntaxError: Unexpected token
I think that the problem is the object property
{"1778":"Bras\u00edlia"}
means an object with an invalid property name, thus json decoding fails;
to prove if this is right try either
use plain text as dataType and log it, it should work [but of course you will not be able to convert it to json]
changeLoadFromDB method so that property name is valid [starts with letter, _ or $], you will have a valid JSON response, but you will need to change the way you use it
it 1778 is an ID, a proper structure should be
{id:"1778",property:"Bras\u00edlia"} and work flawless
give it a try and let us know
EDIT:
as jcaron kindly suggested, i have to fix, this answer: the "1778" is indeed a valid property name, but invalid identifier if dot notation is used.
Since I don't know how jQuery manage this i would suggest to test as above, and see if one of the tests gives results.

JSON.parse give me an error but JSONLint say it's a valid json

I'm trying to make a graphic with jqplot extracting the values vía mysql ajax, I have read so much information about this, i'm IT and to me it's a little embarrasing making this question. It's causing me a big headache :(
I've spent 20 days resolving this but i can't alone myself, anyone can help me please? I have tried almost everything (json.parse, parsejson, getjson, datatype html, datatype json, method get and post.....)
I know it will be easy...
Why crash when i try to do JSON.parse(resultado) ?
http://jsonlint.com/ say it's a Valid Json, but when I try to do JSON.parse he give me an exception saying ("JSON.parse: unexpected character at line 1 column 1 of the JSON data")
It seems is the [ character
Here is the php:
<?php include('conex.php');
$datos=mysql_query("SELECT * FROM Meteorologia");
$arrDatos = array();
while ($rs=mysql_fetch_assoc($datos))
$arrDatos[] = array_map('utf8_encode', $rs);
echo json_encode($arrDatos);
?>
I obtain:
[{"FECHA":"2015-01-01","OZONO":"3","KT":"2","VV":"4"},{"FECHA":"2016-03-03","OZONO":"68","KT":"86","VV":"78"}]
The js is:
try
{
var strHtml = "";
$.ajax({
global: false,
dataType: "html",
async: false,
type: "POST",
url: $("#form").attr('action'),
data: $("#form").serialize(),
success: function(resultado){
alert('success!!'+resultado);
console.log(typeof resultado);
console.log(resultado);
//var datosRecibidos = JSON.parse(resultado);
//var datosRecibidos = jQuery.parseJSON(resultado);
var lista = "";
$.each( resultado, function( key, value ) {
if(value.FECHA == "2015-01-01")
{
alert('si!!');
}
else
{
alert('sino!!');
}
});
},
error: function(data){
alert('Error!!: '+data);
}
});
}
catch(ex)
{
alert("catch!!"+ex);
}
With the $each key value ... can i move inside the array?
After trying a lot of things (changing datatype json,html,..., method get, post...)
I debugging with the address file:///C:/xampp/htdocs/traerdatos/index.html
instead of http://localhost/traerdatos/index.html
So the solution is to CHANGE THE ADDRESS TO LOCALHOST
(Thanks to reformed that helps me with his vision)
Novel error =)

jQuery JSON SyntaxError: JSON.parse only on FIREFOX

Hi Guys the problem is simple but I can't resolve it - it happen only in FIREFOX here is code:
$.ajax({
type: "POST",
url: validUrl,
data: serializedForm,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType(jsonMimeType);
}
},
dataType: "json",
success: function(resp){
console.log(resp);
var arr = jQuery.parseJSON(resp);
}
});
console.log give such answer:
["emailAddress.used", "register.confirmRulesError"]
I have error in:
var arr = jQuery.parseJSON(resp);
Full error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
This happens only in FireFox and I can't find solution.
Response header is: Content-Type application/json;charset=UTF-8
Any ideas how to solve this ?
try without parse json you data.because,
response data look like this,
["emailAddress.used", "register.confirmRulesError"]
if you tring to parse,need key,value pair in json,that is reason it thorw exception.
{["emailAddress.used", "register.confirmRulesError"]}//not allowed.

SyntaxError: JSON.parse: unexpected character for null results

I know that the same topic is asked by several people, but I cannot find an answer for my problem from these questions.
I have the following code,
$.post("show_search_results.php", {location_name: ""+location_name+"", key: ""+key+"", category_id: ""+category_id+"", page_number: ""+page_number+""}, function(data){
if(data.length >0){
var dataArray = JSON.parse(data);
var result_count=(dataArray.root.data.partners).length;
if(result_count > 0){
//block a;
}else if(s_limit==0){
//block b;
}else{
//block c;
}
}});
I am using php as back end. this code works fine in my local server and works fine in live server with the following json.
{"root": {"success":"1","message":"Successfully retrieved data.","data":{"partners":[{"store_name":"Mega Mart (Readymade Brands)","store_address":"Next to SBI, Vyttila, Ernakulam","store_phone":"","item_name":"Festival of Young at 999","item_description":"Megamart celebrates the spirit of being young. Take home 4 groovy T-shirts or 2 stylish shirts or 3 women kurtas for just rupees 999.","item_offer":"999 Offer","offer_expiry":"2014-06-08","tag1":"T-shirt","tag2":"Dress","tag3":"Jeans","store_id":"a9e12c46-ee00-11e3-a5e4-bc305be6e93e"}]}}}
But for this json,
{"root": {"success":"2","message":"no results found","data":{"partners":[]}}}
in live server it shows,
SyntaxError: JSON.parse: unexpected character
var dataArray = JSON.parse(data);
I have tried to remove JSON.parse from my code but it shows
TypeError: dataArray.root is undefined
var array_locations=dataArray.root.data.locations;
Please help me to find a solution.
Thanks.
So you shouldn't really need to be doing JSON.parse by hand - jQuery can do this for you if you tell it to expect JSON. It usually uses the Content-Type header in the return response but you can tell it to parse JSON:
$.post({
url: "show_search_results.php",
data: {
location_name: ""+location_name+"",
key: ""+key+"",
category_id: ""+category_id+"",
page_number: ""+page_number+""
},
dataType: "json",
success: function(data){
// do something with data here...
alert(data.root.message);
}
});
By the way - I tried putting the JSON you specify there into the JSON.parse on the Chrome debug console and it worked fine. There's nothing wrong with that JSON.
Change your condition like this.
if(data.length >0){
var dataArray = JSON.parse(data);
if(typeof dataArray.root != undefined && dataArray.root.success == 1) {
// Success
}
else {
// Failure
}
}

Categories