Uncaught SyntaxError: Unexpected token in JSON at position 0 - javascript

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.

Related

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 =)

Debugging AJAX requests

I am currently trying to figure out how I can find out what errors are in my php script.
I have made a small script which an error on purpose. Using the chrome console I get...
Uncaught SyntaxError: Unexpected token <
However, normally PHP errors would point you to the line in which the error occurs.
Here is my AJAX Request.
var myData = "Hello";
$.ajax({
type: "GET",
url: 'test.php',
datatype: 'json',
data: { data: myData},
success: function(output) {
var result = $.parseJSON(output);
for(var i=0; i<result.length; i++){
console.log(result[i]);
}
}
});
And my PHP script with the syntax error
$data = ($_GET['data']);
echoo boom;
echo json_encode(array($data, "test"));
As you can see, line 2 is the error but the error in my console gives me no information as such.
Thanks
$.ajax({
type: "GET",
url: 'test.php',
datatype: 'json',
data: {},
success: function(output) {
result = output;
for(var i=0; i < result.length; i++){
console.log(result[i]);
}
}
});
By defining the dataType as json the output is already parsed. Parsing the already parsed 'output' again led to the error. So it was a client side / javascript error.
ALso note that - in case an error occurs - the actual error message is parsed too. So you get an array containing the "fragmented" error message from the server ;)
When the error is server side you typically only get an error message (maybe 500 or Server Error) on the client side which is very non-specific. You must debug on the web server. Once I see such an error I check out the web server's error log file (which will show both compile and run time errors).
Please write :
$data = $_GET['data'];
echo boom;
echo json_encode(array($data, "test"));
Instead of :
$data = ($_GET['data']);
echoo boom;
echo json_encode(array($data, "test"));
And write :
$.ajax({
type: "GET",
url: "test.php",
timeout: 6000,
success: function(data) {
json = $.parseJSON(data);
for (var i = 0; i <= json.length-120; i++) {
console.log(json[i]);
}
}
});
Use the debugging tools in your browser. Specifically look for a tab or set of functionality for monitoring network requests. This will show you the actual request and response to and from the server in your AJAX.
What's happening here is your PHP code is generating an error, which results in returning some kind of HTML to the browser (possibly showing the error message). However, look at what you're doing with the response:
var result = $.parseJSON(output);
If output is HTML and not JSON, then this code will fail with an error. Since JSON syntax doesn't use < but HTML does, I would expect you to get the error:
Uncaught SyntaxError: Unexpected token <

Parsing Mandrill JSON Response with jQuery / Javascript

I have a php script which is sucessfully connecting to and sending an email through the Mandrill API. As dumb as it sounds, I can't figure out how to parse the following JSON reponse:
Array
(
[0] => Array
(
[email] => matt#mattblum.com
[status] => sent
[_id] => eedced1b58e24668907024e937afeabd
[reject_reason] =>
)
)
Full ajax call is:
$.ajax({
type: 'POST',
url: 'mandril.php',
data: formData.serialize(),
success: function(returnedData) {
var response = returnedData;
status = response[0]['status']; // I've also tried different combos of this
if(status == "sent") {
msgs('Message sent!');
var alreadySent = true;
} else {
msgs(response);
}
},
error: function(e) {
console.log(e);
}
The code I've tied to read the 'status' element:
console.log(response[0]['status']);
console.log(response[0][1]);
console.log(response[0][0]['status']);
console.log(response[0][0][1]);
Another thing I don't understand is that:
var response = returnedData;
console.log(response[0]);
Returns a capital 'A' and nothing else.
I'm sure it's something dumb that I'm doing but any help is greatly appreciated.
Matt,
Looks like your PHP array syntax is being captured as text and sent as a response to your post. If you specify JSON on the Mandrill/PHP side (and the ajax/jquery side) your jquery call should be able to parse the response.
console.log(response[0]) is returning 'A' because that's the first character of the string.
Add 'json' on the query side and json_encode($response) on the php side.

jQuery returning "parsererror" for ajax request

Been getting a "parsererror" from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.
My project is in MVC3 and I'm using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.
Dropdown: (this loads the "Views" from the list in the Viewbag and firing the event works fine)
#{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
#Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
Javascript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
The above code successfully calls the MVC method and returns:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
But jquery fires the error event for the $.ajax() method saying "parsererror".
I recently encountered this problem and stumbled upon this question.
I resolved it with a much easier way.
Method One
You can either remove the dataType: 'json' property from the object literal...
Method Two
Or you can do what #Sagiv was saying by returning your data as Json.
The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json, so the parser fails when parsing it.
So if you remove the dataType: json property, it will not try to parse it as Json.
With the other method if you make sure to return your data as Json, the parser will know how to handle it properly.
See the answer by #david-east for the correct way to handle the issue
This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.
I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete event and then checking the status value. e.g:
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
You have specified the ajax call response dataType as:
'json'
where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.
The best approach that I would recommend is to change the dataType to:
'text'
and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'text',
data: {viewID: $("#view").val()},
success: function (data) {
try {
var output = JSON.parse(data);
alert(output);
} catch (e) {
alert("Output is not valid JSON: " + data);
}
}, error: function (request, error) {
alert("AJAX Call Error: " + error);
}
});
the problem is that your controller returning string or other object that can't be parsed.
the ajax call expected to get Json in return. try to return JsonResult in the controller like that:
public JsonResult YourAction()
{
...return Json(YourReturnObject);
}
hope it helps :)
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's ignoring the underlying issue. If you're confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
Your JSON data might be wrong. http://jsonformatter.curiousconcept.com/ to validate it.
Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.
I don't know if this is still actual but problem was with Encoding. Changing to ANSI resolved the problem for me.
If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false.
As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.
$.ajax({
url: '/Test/Something/',
type: 'GET',
dataType: 'json',
cache: false,
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
you should remove the dataType: "json". Then see the magic... the reason of doing such thing is that you are converting json object to simple string.. so json parser is not able to parse that string due to not being a json object.
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
incase of Get operation from web .net mvc/api, make sure you are allow get
return Json(data,JsonRequestBehavior.AllowGet);
If you don't want to remove/change dataType: json, you can override jQuery's strict parsing by defining a custom converter:
$.ajax({
// We're expecting a JSON response...
dataType: 'json',
// ...but we need to override jQuery's strict JSON parsing
converters: {
'text json': function(result) {
try {
// First try to use native browser parsing
if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
return JSON.parse(result);
} else {
// Fallback to jQuery's parser
return $.parseJSON(result);
}
} catch (e) {
// Whatever you want as your alternative behavior, goes here.
// In this example, we send a warning to the console and return
// an empty JS object.
console.log("Warning: Could not parse expected JSON response.");
return {};
}
}
},
...
Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)
With this custom converter, .done()/success will be triggered as long as the request was otherwise successful (1xx or 2xx response code).
I was also getting "Request return with error:parsererror." in the javascript console.
In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.
String encodedString = getEncodedString(text, encoding);
view.setTextAreaContent(encodedString);
I have encountered such error but after modifying my response before sending it to the client it worked fine.
//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response); // Sending to client
//Client side
success: function(res, status) {
response = JSON.parse(res); // Getting as expected
//Do something
}
I had the same problem, turned out my web.config was not the same with my teammates.
So please check your web.config.
Hope this helps someone.
I ran into the same issue. What I found to solve my issue was to make sure to use double quotes instead of single quotes.
echo "{'error':'Sorry, your file is too large. (Keep it under 2MB)'}";
-to-
echo '{"error":"Sorry, your file is too large. (Keep it under 2MB)"}';
The problem
window.JSON.parse raises an error in $.parseJSON function.
<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>
My solution
Overloading JQuery using requirejs tool.
<pre>
define(['jquery', 'jquery.overload'], function() {
//Loading jquery.overload
});
</pre>
jquery.overload.js file content
<pre>
define(['jquery'],function ($) {
$.parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
/** THIS RAISES Parsing ERROR
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
**/
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "#" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
$.error( "Invalid JSON: " + data );
}
return $;
});
</pre>

Categories