SyntaxError: JSON.parse: unexpected character for null results - javascript

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

Related

SyntaxError: Unexpected '' on line 1 on validator JSONLINT

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

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.

Retrieving a JSON.parse() string from a server

I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression

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 AJAX JSON object not working

I'm having some trouble with my AJAX request.
The problem is with the JSON object named html.
AJAX request:
$.ajax({
url : 'index',
type : 'POST',
dataType : 'json', // Makes no difference
data : {
method : 'saveModule',
html : content
},
success : function(i){
console.log(i);
}
})
I know it's about the html JSON object because if I remove it the request will succeed.
This is what it looks like with firebug's console.log();
the object is stored within [ ], is that normal?
[Object { name="Home", link="/home"}, Object { name="Work", link="/work", childs=[3]}, Object { name="Contact", link="/contact", childs=[2]}]
The childs are JSON objects as well.
Please help, it's driving me crazy!
The error I'm getting with the Web Console:
[11:58:47.215] uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://localhost/mcms/htdocs/templates/resources/js/jquery-1.6.3.min.js :: <TOP_LEVEL> :: line 5" data: no]
The content var is made from this:
var content = mcms.module.analyse(obj); // obj is a dom element, in this case a UL with sub ULs inside LIs
The function itself:
analyse : function (that) {
return $(that).children('li').map(function() {
var b = {
name: $(this).children('a').text(),
link: $(this).children('a').attr('href')
};
if ($(this).children('ul').size() > 0) {
b.childs = mcms.module.analyse($(this).children('ul'));
}
return b;
});
}
I've found the problem and fix!
The problem was that the .map() function returns an array around the JSON object.
So I made a JSON object with a counter around the map to capture it and return it :)
Thanks for helping everyone!
analyse : function (that) {
var b = {};
var x = 0;
$(that).children('li').map(function() {
b[x] = {
name: $(this).children('a').text(),
link: $(this).children('a').attr('href')
};
if ($(this).children('ul').size() > 0) {
b[x].childs = mcms.module.analyse($(this).children('ul'));
}
x++;
});
return b;
}
I'm not so sure about the method parameter. If that is the method you are looking to call, you can as well include that in your URL, right?
Well, your current call to $.ajax doesn't look exactly right. It should be something along the lines of:
$.ajax({
url : 'index',
type : 'POST',
data : <data to be sent>
dataType : <Default: Intelligent Guess (xml, json, script, or html)>
success : function(i){
console.log(i);
}
})
More info on the jQuery website: http://api.jquery.com/jQuery.ajax/
EDIT
Ok, I see you corrected the call. This looks better now. Where does content come from and what's in it before it is converted into a JSON object?
EDIT2
Well, I think this answer should be of help to you: Post Nested Object to Spring MVC controller using JSON

Categories