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);
};
Related
Sorry but I spent a half a day practicing first with gadgets.io.makeRequest, and can not understand why the request response contains an error. The code is Javascript working as OpenSocial gadget:
requestURI = "https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.com%3A9443%2Frm%2Fprocess%2Fproject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg";
makeGETRequest(requestURI);
...
function makeGETRequest(url) {
try {
var params = {};
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
params[gadgets.io.RequestParameters.HEADERS] = {
"Accept" : "application/rdf+xml",
"OSLC-Core-Version": "2.0"
}
gadgets.io.makeRequest(url, function(obj) {
console.log("===== HTTP REQUEST START =====");
console.log("Method : GET");
console.log("URL : " + url);
console.log("Response : " + obj.text);
console.log("====== HTTP REQUEST END ======");
}, params);
}
catch(err) {
console.log("Can not perform HTTP request because of error: " + err.message);
}
};
When I do the same request with REST Client in Firefox, everything works properly. But if I do that with the code above, then I get an error in the log (abbreviated):
===== HTTP REQUEST START =====
common.js:311 Method : GET
common.js:312 URL : https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.…roject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg
common.js:313 Response : {"errorMessage":"Illegal character in query at index 178: https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.com%3A9443%2Frm%2Fprocess%2Fproject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg","errorClass":"java.lang.IllegalArgumentException","errorTrace":["java.net.URI.create(URI.java:871)","org.apache.http.client.methods.HttpGet.<init>
...
common.js:314 ====== HTTP REQUEST END ======
I tried to replace greater and less symbols by their hex values but there's no result. And there's no ideas currently.
May be somebody could make a fresh sight to the code and define the problem on the fly. Help me please, I'm at a dead end.
Thank you very much in advance for any advice!
The error in your Response indicates the Java system on the server side can't create a valid URI from your query. Therefor it throws back an error
My best guess would be the dot just before query=true in oslc.query=true. And therefor all following uses of oslcDOT .
From RFC 1738 specification:
Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.
I discovered that gadgets.io.makeRequest isn't very stable as I would like to expect. May be I do some wrong but sometimes this function completes without any feedback and without starting the response function in the parameters. I changed to next code:
function makeGETRequest(urlValue) {
try {
$.ajax({
url: urlValue,
type: 'GET',
dataType: 'text',
headers: {
'Accept': 'application/rdf+xml',
'OSLC-Core-Version': '2.0'
},
success: function (result) {
var data = result;
},
error: function (error) {
console.log("Can not perform HTTP request because of error: " + error.message);
}
});
}
catch(err) {
console.log("Can not perform HTTP request because of error: " + err.message);
}
};
And there's no problem!
I'm using p5.js to do some drawing using data from json fed by my Django backend. I have a my draw function defined at the base level of my html doc in the script element like so:
function draw(json) {
if (json["leaf_text"]) {
stroke(100)
ellipse(json["leaf_center_x"], json["leaf_center_y"], json["leaf_height"], json["leaf_width"]).rotate(json["leaf_rotate"]);
}
if (json["twig_text"]) {
stroke(100);
console.log("drawing twig....");
line(json["twig_base_x"], json["twig_base_y"], json["twig_tip_x"], json["twig_tip_y"]);
}
if (json["branch_text"]) {
stroke(150);
line(json["branch_base_x"], json["branch_base_y"], json["branch_tip_x"], json["branch_tip_y"]);
console.log("x1 " + json["branch_base_x"]);
console.log("x2 " + json["branch_base_y"]);
console.log("y1 " + json["branch_tip_x"]);
console.log("y2 " + json["branch_tip_y"]);
}
if (json["trunk_text"]) {
stroke(255);
line(json["trunk_base_x"], json["trunk_base_y"], json["trunk_tip_x"], json["trunk_tip_y"]);
}
}
This function is called upon receipt of a successful ajax response as follows. My problem is, I get a error in the js console because of the draw function.
TypeError: json is undefined
My understanding is that (please correct me where I am wrong) the 'draw' function is agnostic concerning whether or not 'json' exists or not and will wait and see what sort of object it is passed before it begins complaining that the parameter is not defined. Is this not the idea of a function in javascript?? I must be missing something. If this is the case, why would it complain that json is not defined?
if (json["leaf_text"]) {
$("#grow").click(
function(e) {
console.log("attempting ajax...");
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var open_parens = ($("#txt").val()).indexOf("(");
var close_parens = ($("#txt").val()).indexOf(")");
var child = $("#txt").val().slice(0, open_parens);
var parent = $("#txt").val().slice(open_parens + 1, close_parens);
$.ajax({
url: window.location.href,
type: "POST",
data: {
csrfmiddlewaretoken: csrftoken,
child: child,
parent: parent,
mode: "grow"
},
success: function(json) {
setup();
draw(json);
...
}
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
});
If you use import called json, you should use different name as parameter for draw function (for example: draw(json_bar) or, in import, re-name json (for example: import json as json_foo).
I'm a complete newby to JS. Trying to use SharePoint REST API to display a link list in a footer. Keep getting this error no matter what I do. It is for this line LoadFooterLinks(results.d.results);
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
LoadFooterLinks(results.d.results);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}
A few things:
How do you know you have an "error"?
Is is a Javascript Exception?
WHAT IS the error or Exception?
How do you know the error isn't with your LoadFooterLinks() function?
Most likely your results are NOT what you are expecting. You're obviously:
Successfully making a connection and request
But, you can't be sure what's coming back. It could be:
empty string
null
malformed
Hitting F12 in most browsers will bring up that browser's Developer mode/built-in JS console
My code changes below should help you debug by outputting to the console for you.
Things to NOTE about the code changes:
The difference between:
catching a JavaScript runtime exception/error using try-catch vs.
outputting the string variable arbitrarily named "error" in the failure callback method of the $.ajax object
Print an exception to to the console doesn't require console.err()
If you want to show a string as an error in the console use console.err(), not console.log.
Null is an object, not a datatype or primitive like the other ones in JavaScript. For Example,
boolean
string
undefined
number
New Code
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl +
"/_api/lists/getbytitle('Footer Links')/items/?
$orderby=Display_x0020_on_x0020_Homepage"
;
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
if (!results) { // should handle null and empty strings
try{
LoadFooterLinks(results.d.results);
}
catch (e){ // catch any JavaScript runtime exception (error)
console.log(e); // print the error to the console
// (hit F12 in most browsers to see
// the console BEFORE you refresh
// the page to run your code)
}
}
else {
var msg = "The 'results' variable is ";
var varType = typeof(results);
if (varType == "object") {
msg += "NULL";
}
else {
msg += varType;
}
}
},
error: function (error) {
// this 'error' variable can be named
// anything you'd like and is a string
// description of the AJAX error.
// This description comes from $.ajax -
// which is part of jQuery (a JS library).
// This "error" is not a native JS
// exception; therefore, you wouldn't
// use a TRY-CATCH. Also, since it's
// only a string, if you want to show it
// as an error in the console, you should
// use `console.err`, not `console.log`.
console.err("Error in getting List: (0)", error);
}
});
}
What you are basically doing is making a request to the "/_api/lists/getbytitle" method.
When that method returns a response, it will do so as an object named "results", as you can see under the "success" callback.
What you are doing afterwards is reading a property called "d" and within "d" you are trying to obtain the value of property called "results".
What the error is saying is that "d" is undefined therefore it cannot retrieve the value of "results" from "d".
I suggest you check what is inside the object "results" of the success callback.
For SharePoint API result, you would need to parse the JSON response to convert it to Javascript object. I've modified your code a bit to make it work in this case.
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (response) {
var svcData = JSON.parse(response.data).d.results;
LoadFooterLinks(svcData);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}
guys!
It is very strange thing. This code normally works in all browsers I know, except IE8 (may be IE7 too).
function xajax_xfrmproc(sender, eventname, data, formname, data2) {
var dt = {};
dt.__xr = 1; // AJAX request flag
dt.__sender = sender;
dt.__eventname = eventname;
dt.__data = data;
dt.__formname = formname;
dt.__data2 = data2;
$.ajax({
type: 'POST',
url: '',
data: dt,
error: function(req, text, error) {
alert('AJAX Error: ' + text + ' | ' + error + ':' + "\n" + req.responseText);
},
success: function (json) {
jxr_decode(json);
},
dataType: "json"
});
}
It calls error method and writes: "AJAX Error: error | Error: Invalid argument".
You can test is online here: http://stat.8-800.su (enter any values and press "Войти в статистику" button).
I check in over all internet but not found anything useful.
I've tried to set AddDefaultCharset utf-8, nothing happens.
This is a stab, but try using the actually URL instead of the empty string. So
url: '/',
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?