What is the reason for this error? How do I fix?
error with Google Chrome :
An error has occured: [object Object] parsererror SyntaxError:
Unexpected token ILLEGAL
error with opera:
An error has occured: [object Object] parsererror SyntaxError:
JSON.parse: Unable to parse value:
error with ie9:
An error has occured: [object Object] parsererror SyntaxError:
Invalid character
and ...
js code:
$('#hotel').keypress(function () {
var dataObj = $(this).closest('form').serializeArray();
$.ajax({
url: 'http://localhost/mehdi/admin/tour/search_hotel',
data: dataObj,
dataType: 'json',
success: function (data) {
$("#suggestion_tab").html('');
$.each(data.suggestions, function (a, b) {
$("#suggestion_tab").append('<li>' + data.b + '</li>');
});
// Display the results
///alert(data);
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
php:(CI_Controller)
function search_hotel(){
$searchterm = $this->input->post('search_hotel');
$result = $this->model_tour->search_hotel($searchterm);
while($row = mysql_fetch_assoc($result))
{
$output[] = $row;
}
echo json_encode(array('suggestions' => $output));
}
CI_Model
function search_hotel($searchterm)
{
return mysql_query("select * from hotel_submits where name LIKE '".$searchterm."'");
}
Your JSON contains invalid syntax.
You need to look at the actual JSON and fix the error.
Also make sure, that your response is in UTF.
This can happen due to session timeout.
Try using http://jsonlint.com/ to see if the JSON packet is valid. It looks to me like you need to json_encode every one of the rows from the database, and then add those encoded packets to another JSON array?
Related
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.
I have the following ajax call where I am passing the data in JSON format and when this code gets executed I get the error shown below,I showed the Console.log(data_cp) below and I validated it in http://jsonlint.com/ and it is a validated input?what am I missing here?how to fix this error?I looked at other posts like json parsing error syntax error unexpected end of input but couldnt figure out...
$.ajax({
dataType: "json",
type: "POST",
contentType: "application/json",//note the contentType defintion
url: "scripts/cherrypick.py",
data: JSON.stringify(data_cp),
//data: data_cp,
error : function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
},
success: function(message){
console.log("cherypick sucess");
}
Serverside python script:-
#!/usr/bin/python
import os
import sys
import json
print "Content-type: application/json\n\n"
...............
...............
def main():
result = {'success':'true','message':'The Command Completed Successfully'}
cherrypicklist = []
cherrypickfaillist = []
myjson = json.load(sys.stdin)
gerritlist = myjson['gerrits']
resource = r'buildserver'
buildlocation = r'cd /local/mnt/workspace/user/buildlocation ; '
for gerrit in gerritlist:
cmd = buildlocation
project,ref = fetchgerritproject(gerrit, connection=None)
proj_path = getprojectpath(project)
cmd += 'cd ' + proj_path + ' ;'
new_cmd = ' gknife am-or-cp ' + gerrit
pick_cmd = cmd + new_cmd
errorlist =''
errorlist = cherrypick(resource,pick_cmd)
if len(errorlist) <= 2:
cherrypicklist.append(gerrit)
else:
chk_cmd = cmd + ' git checkout -f'
connection = ssh_connect(resource)
errorlist = execute_command(connection,chk_cmd)
cherrypickfaillist.append(gerrit)
for gerrit in cherrypicklist:
cmd = buildlocation
project,ref = fetchgerritproject(gerrit, connection=None)
proj_path = getprojectpath(project)
cmd += ' cd ' + proj_path + ' ;'
errorlist = resetgerrit(resource,cmd)
errorlist = execute_command(connection,chk_cmd)
print json.dumps(result)
#return
if __name__ == "__main__":
main()
Error:-
SyntaxError: Unexpected end of input
Console.log(data_cp) output:-
{"gerrits":["1258565","1279604"]}
As per definition of error method from Jquery docs, you get error from server side or if call is not successful.
So it means you are getting error from server. Check the server code.
Definition of Error method from JQuery
error Type: Function( jqXHR jqXHR, String textStatus, String
errorThrown ) A function to be called if the request fails. The
function receives three arguments: The jqXHR (in jQuery 1.4.x,
XMLHttpRequest) object, a string describing the type of error that
occurred and an optional exception object, if one occurred. Possible
values for the second argument (besides null) are "timeout", "error",
"abort", and "parsererror". When an HTTP error occurs, errorThrown
receives the textual portion of the HTTP status, such as "Not Found"
or "Internal Server Error." As of jQuery 1.5, the error setting can
accept an array of functions. Each function will be called in turn.
Note: This handler is not called for cross-domain script and
cross-domain JSONP requests. This is an Ajax Event.
ASP.NET MVC4 shoping cart application implements error logging from client browser using
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
$.post('/Home/Error',
{
"errorMsg": errorMsg,
"url": url,
"lineNumber": lineNumber,
"column": column,
"errorobj": JSON.stringify(errorObj)
});
This logs strange errors about token o :
Error Uncaught SyntaxError: Unexpected token o
urls and column numbers vary a bit:
Line 1 Column 2
Line 1 Column 10 Object {}
Line 1 Column 10 Object {}
Line 1 Column 9 Object {}
Line 1 Column 1 Object {}
Line number is 1 always, object is empty.
There are 4 different column numbers: 1,2,9,10
How to find line in javascript which causes this exception ?
Exception occurs in client browser where there is no access. Only way is to
send information about js code line to browser.
Those pages contain few ajax calls. /Store/Browse contains ajax to add item to cart:
request = $.post('/Store/AddToCart',
serializedData, function (response) {
$("#cart-status").text(response.Total);
$inputs.prop("disabled", false);
var xx = $form[0].quantity;
$($form[0].quantity).css("background-color", "green");
showMessage(response.Message);
showFadeOutMessage(response.Message);
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert('Error ' + textStatus);
})
.always(function () {
$inputs.prop("disabled", false);
});
It is possible to add lastLine assignments to code like
var lastLine;
lastLine="request = $.post('/Store/AddToCart";
request = $.post('/Store/AddToCart',
serializedData, function (response) {
lastLine='$("#cart-status").text(response.Total)';
$("#cart-status").text(response.Total);
lastLine='$inputs.prop("disabled", false)';
$inputs.prop("disabled", false);
...
and send lastLine value to server in window.onerror but this requires lot of code changes manually.
Is there a better way to find line here error occurs and maybe stack trace also ?
window.onerror is different between IE, Chrome and Firefox. Your code will work in IE. This code will work in IE and chrome.
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
$.post('/Home/Error',
{
"errorMsg": errorMsg,
"url": url,
"lineNumber": lineNumber,
"column": column,
"errorobj": errorObj ? errorObj.stack : ''
});
In Chrome errorObj contains three properties: name, stack and message- but all are getter. JSON.parse doesn't handle functions and getter is a function.
For example (Chrome only!)
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
console.log(JSON.stringify(errorObj)); // {}
console.log(errorObj.stack); //SyntaxError: Unexpected token o
// at Object.parse (native)
// at foo (http://www.example.com/index.js:8:10)
// at ...
console.log(errorObj.message); // Unexpected token o
console.log(errorObj.name); // SyntaxError
}
In IE errorObj it's simple object. But errorObj.stack is clearer.
Firefox does not send errorObj argument. You need wrap the code with try catch (or override JSON.parse and wrap the call with try catch), and send e.toString() and e.stack. For example:
var bckJSON = JSON.parse;
JSON.parse = function () {
try {
bckJSON.apply(argumetns};
} catch (e) {
// send e.toString() + '\n' + e.stack
}
}
Sorry about previous non-useful answers...
The error 'Error Uncaught SyntaxError: Unexpected token o' is occur when you invoke JSON.parse with object.
Probably this code happens -
JSON.parse({});
JQuery, in some cases, use $.parseJSON to convert ajax queries without check if the data is string. I don't know when this happens.
You can workaround in this way:
(Use $.parseJSON because it handle browser without JSON library)
JsonParseFix.js
function isString(value) {
return Object.prototype.toString.call(value) === "[object String]";
}
var bckJSONparse = $.parseJSON;
$.parseJSON = function(text, reviver) {
if (!isString(text)) {return text};
bckJSONparse.apply(arguments);
};
test.js
function test(value, message) {
try {
$.parseJSON(value);
console.log('Test succeed: ' + message);
} catch (e) {
alert('Test failed: ' + message);
}
}
test({}, 'Empty object');
test('<', 'UnSupported strings'); // Failed!
Angular solve this in a similar way (angular.fromJson documentation).
(Sorry about my english...)
Based on Elad's andwer and comments I created the following method which returns call stack in IE, Chrome and FireFox:
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
var stack;
// Firefox does not send errorObj argument. Wrap the code with try catch
// and send e.toString() and e.stack.
try {
stack = errorObj ? errorObj.stack : '';
} catch (e) {
stack = e.toString() + " stack " + e.stack;
}
$.ajax('/api/errorlog?' + $.param({
errorMsg: errorMsg,
url: url,
lineNumber: lineNumber,
column: column
}),
{
data: JSON.stringify({ stack: stack }),
type: 'POST',
dataType: 'json',
contentType: "application/json"
});
alert(errorMsg + ' Line ' + lineNumber + ' Column ' + column + '\n\n' + stack);
};
I am sending an ajax call to my server, where parameter is "general" or any text, for a search query, why is it always giving error. The response is in JSON, and I have already mentioned it, any issues with the code below? Any help will be highly appreciated
$.ajax({
url : "${kb_endpoint_url}",
dataType : 'json',
data : { search_query : queryValue }, // queryValue = general
success : function(data) {
console.log("success");
},
error: function ( xhr, status, error) {
console.log( " xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error );
}
This prints: xhr.responseText: undefined //status: SyntaxError: JSON.parse: unexpected character //Error: undefined
Edit: I tried changing the type to application/json and now the console prints
xhr.responseText: undefined //status: No conversion from text to application/json //Error: undefined
xhr.responseText: undefined //status: SyntaxError: JSON.parse: unexpected character //Error: undefined
I think ; this error means that the response coming back from your URL is not JSON, there's an error attempting to parse it as such.
Either look in your network panel (easier), or adjust your error handler to see what response your server is actually returning, by looking at the responseText
If the server is returning the text undefined, this is not valid JSON and cannot be parsed.
Only null is valid in JSON format, so trying to parse undefined will give this error.
For examples:
JSON.parse("undefined"); // Throws an error, "Unexpected token u"
JSON.parse("null"); // Returns null
If you comment dataType : 'json', your ajax runs properly. Your response is not in JSON format.
$.ajax({
url : "${kb_endpoint_url}",
dataType : 'json',
type : 'post',
data : { search_query : queryValue }, // queryValue = general
success : function(data) {
console.log("success");
},
error: function ( xhr, status, error) {
console.log( " xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error );
}
});
Another file (mentioned url )
<?php
echo json_encode($_POST);
?>
i've got a simple ajax call:
function message(){
$.ajax({
type: "GET",
url: "/file/timestamp="+ timestamp,
async: true,
cache: false,
success: function(data){
var json = eval('('+data+')');
console.log(json);
}
});
}
and i get an error Uncaught SyntaxError: Unexpected token < at this line: var json = eval('('+data+')');
any ideas?
thanks.
edit:
some more details from the error:
$.ajax.successajax.js:9
f.Callbacks.njquery.js:2
f.Callbacks.o.fireWithjquery.js:2
wjquery.js:4
f.support.ajax.f.ajaxTransport.send.d
here is some php if is helping
public function fileAction()
{
$this->getHelper('viewRenderer')->setNoRender();
$filename = '/test/text.txt';
$front = Zend_Controller_Front::getInstance();
$data = $front->getRequest()->getParams();
$lastModif = !empty($data['timestamp']) ? $data['timestamp'] : 0;
$currentModif = filemtime($filename);
while($currentModif <= $lastModif){
usleep(10000);
clearstatcache();
$currentModif = filemtime($filename);
}
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentModif;
echo json_encode($response);
}
if i run this action i get json: {"msg":"message","timestamp":1331599879} but for some reason the response is not this but some html
It depends on what's inside data. You're running eval, so whatever's in data is being run. Please post the data here,.
What are you expecting to be returned in as data? Running eval will try to execute (data) which doesn't seem like it will be proper javascript. If you just want to store a string you can do:
var json = "(" + data + ")";
jholloman almost had it...
var json = eval("(" + data.responseText + ")");