Error handling and saving logs to text files - javascript

I want to do error handling in javascript.
I want to log the error occurred in the javascript.
I don't want to use the database to store the errors.I want to store all the error in a txt file(that txt file should be present in the server where that website is hosted. So that others can't access that file.
How to do the above requirement.
I searched in Google and find
function WriteToFile() {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\Test.txt", true);
s.WriteLine('Hello');
s.Close();
}
this is also not working in all conditions.
1. You're using a non-ie browser (which doesn't support activex objects)
2. you're using an ie browser on an xp machine with sp2 installed and the activex object is being blocked
So please help me to solve this problem.
Thanks in advance.

Use a try/catch to detect the error first of all:
try
{
// code that could error here
}
catch(err)
{
// do an ajax call to the server
}
In the catch block, you could do an ajax call to the server. On the server you will need some server side script (such as PHP, ASP etc etc) to process the request and log the error to a local text file. In the catch block above, err.message will give you the error message string which you can include in your ajax call.

HI you can use alternative way to handle the error as below code
jQuery.ajax({
type: "POST",
url: "urlpage",
dataType: "html",
data: "types":$("#catid").val(),
success: function (response) {
alert("Successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
When any error occurred you can call another ajax function or same function once again.
This works mostly in all ajax call to handle error, Try it.

Related

$.ajax() returns syntax error: Unexpected end of json input

So I'm working on a website where I have to implement a chat, currently the whole thing is running on localhost.
I'm getting this error:
SyntaxError: Unexpected end of JSON input
and can't figure out why. I have googled a little but can't find an answer, that actually works. I actually did this yesterday, on another computer and that worked super, but today it won't work and I can't figure out why.
Thank you for the great answers.
$(function() {
updateChat("updateChat", null);
$(".chat-form").submit(function(event) {
event.preventDefault();
if ($(".chat-form input").val() != "") {
updateChat("sendMessage", $(".chat-form input").val());
}
});
setInterval(function() {
updateChat("updateChat", null);
}, 3000);
function updateChat(method, message) {
$.ajax({
type: "POST",
url: "action/chat.php",
data: {
function: method,
message: message
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function (request, status, error) {
console.log(error);
}
})
}
})
Most likely there's an error or warning in your PHP code being displayed, and because you are expecting only json, that causes the syntax error.
There are a few ways to find out what's going on:
open the developer console in your browser and see what the response is the network tab
check your PHP error log
temporarily change your dataType to html and you'll see your console.log(data)
I was getting this error due to my backend php function NOT returning a response as it should have been. It was returning nothing. My parent function that should have been returning the response was calling a child function that WAS returning a response, but the parent function wasn't passing that child return back to the ajax call.
Another possible culprit for these type of errors could be an improper python "shebang" on your back-end (server side) script.
In my particular case I had ajax call to python cgi script via Apache web server and I could not find a more descriptive error message at front-end debug tools. However, Apache logs indicated that the back-end script had problems importing a one of the python scripts because the interpreter did not recognize it. After checking the "shebang" of that back-end script sure enough it had the wrong interpreter specified because I just copied a template file over and forgot to modify it..
So, check your "shebang" at the top of your script to make sure it points to correct interpreter. Example:
For MVC controller you must return a valid JsON
return new JsonResult() { Data = new { test = 123 } };
instead of
return new JsonResult();

return javascript error via cakephp

$.ajax({
type: "POST",
url: "/find",
data: {coupon_name:value},
success: function(response) {
alert("success")
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
What do I "echo" within my PHP page to throw an error? Basically I'm using the ajax function to count the number returned, if <1 it needs to throw an error back to the JS.
The jQuery specification defines .error() as:
A function to be called if the request fails.
A failure HTTP code is one in the 400s or 500s, so a CakePHP equivalent of:
<?php
http_response_code(500);
?>
should trigger it.
That said, I'm not sure that throwing an error is necessarily correct in your circumstances - your query hasn't actually errored, it just has returned zero results. So you may be best handling this within the .success() function anyway.
I suggest you leave the error for the real HTTP-related emergencies, and handle your code logic in your response. The easiest approach is making the response into JSON, returning an error component in the JSON if you encounter an error, and manually checking for its presence.
That said, you can use $this->controller->response->statusCode(400) (in CakePHP) or similar to send a status code that will trigger an error clause. But I recommend against it.

Debugging Javascript / AJAX requests

I saw a lot of questions and answers on how to debug javascript with chrome, firebug etc...
but this all involves a pre-loaded js file.
Is there a way to debug (step by step, not with alerts) a js script that comes as a response to a Rails AJAX request?
Assuming that you have access to edit the file that Rails returns, you can temporarily insert a debugger; statement.
Then, when you have your browser's debugging console open as you receive the AJAX response, JS execution will halt and you can step through execution in the debugger.
If you change your response to include the debugger keyword it should hit that as a break point. You can ONLY examine the results of the ajax call from within the success handler itself. So in this case the response would be:
var test = "it isn't working";
var response = $.ajax({
type: 'GET',
url: 'jquerydemo.php',
success: function(data, textStatus, xhr){
debugger;
//alert("it's working");
},
error: function(xhr, textStatus, errorThrown){
debugger;
//alert("Error detected");
}
});
Obviously don't forget to remove that when it goes live. :D

$.post is not working (anywhere)! Why?

My calls to $.post are not working all over my code. I'm not sending the request to other domains and, actually, I'm doing everything localhosted. My localhost alias was automatically defined by the Mac OS X 10.8 as ramon.local and I'm requesting from http://ramon.local/linkebuy_0.7/resourceX to http://ramon.local/linkebuy_0.7/resourceY. There are no errors on Chrome's console.
The server side doesn't receive the request and I can check it by accessing directly from the browser (typing the URL).
It's not just one call that is not working, none of them are. They were all working days ago and I'm suspicious that I accidentally changed something on my local settings. What could it be?
Here's an example of what I'm facing:
$.post(
<<CORRECT URL INSIDE THE DOMAIN>>,
{},
function(response) {
console.log('THIS SHOULD BE PRINTED ON CONSOLE');
alert('THIS SHOULD BE POPPED UP');
}
);
I don't get the alert, neither the console message while running the code above. So I tried the following:
$.support.cors = true;
$.ajax({
url: "http://ramon.local/linkebuy_0.7",
dataType: "json",
type: "GET",
crossDomain: true,
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
alert(error + " - " + status);
}
});
I just came with $.support.cors = true; and crossDomain: true to check if it was a cross domain issue. So I was alerted No Transport - error same way as before.
What can I do to solve that?
Thanks in advance.
Try this and see if you are getting any alert:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("your url", function() {
alert("success");
}).success(function() {
alert("second success");
}).error(function() {
alert("error");
}).complete(function() {
alert("complete");
});
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
alert("second complete");
});​
Well, I solved the problem in a very strange way.
I deleted the JQuery file and downloaded it again, replacing the old one. Happens it worked out.
So, if you're:
Making AJAX requests that are not cross-domain;
Using JQuery for it (e.g. $.post, $.get, etc);
Getting No Transport AJAX error
Then re-download and replace you're JQuery source.
Else, if you're making cross-domain requests (not this case), then look for JSONP and try to set $.support.cors = true; at the beginning of you're code.
Thanks everyone for the comments and answers.

Debugging IFrame content

I'm having a problem with a page that works fine by itself, but when it's embedded in a iFrame in a corporate webpage (that I don't control) it chokes in IE9 (but not IE8).
The page uses jQuery to make an AJAX call and KnockoutJS to bind content for display. The page passes parameters in a GET request to my server with responds with AJAX, and it seems that it chokes when getting the data back from the server. The data is correct and correctly formatted, however, when this code executes:
$.ajax({
url: this.serviceURL + parameters,
dataType: 'json',
success: callback,
timeout: 3000,
error: function (jqXHR, status, errorThrown) {
if (status == "timeout") {
error("The connection to the server timed out.\nEither the server is down or the network is slow.\nPlease try again later.");
}
else {
error("An error occurred while trying to communicate with the server.\n " + errorThrown);
}
}
});
In IE9, I always hit the "An error occurred..." branch with the errorThrown of "SyntaxError: Invalid character", which tells me nothing.
Anybody got any suggestions on how to go about debugging this problem? I used Fiddler to look at what was being sent to and returned by the server, and everything looks fine on that end.
Update: After sleeping on it for a while, I started fresh today. What I've determined is that for some reason, when my page is iFramed, instead of getting the JSON response:
"{"Foo":true,"Bar":true}"
I'm actually getting (from forcing an error in the error handler so I could inspect the state of the jqXHR.responseText) is:
" {"Foo":true,"Bar":true}"
Which if, using the console, I try feeding to JSON.parse, gives me an error. So the question is, where the heck is that leading space coming from? If I run this in Firefox, I see the correct response from the server (no space) and if I run this outside of the iFrame, I see no leading space. So I don't think it's coming server side. Somewhere in the mess of JS running on the parent page and my page, it's inserting a leading space.
Update 2: A closer examination reveals that jqXHR.responseText.charCodeAt(0) is 65279, so it's not actually a space (although it displays as one) it is the byte order mark. But why is it there now (and not before) and why is it causing a problem?
I couldn't figure out the reason for this problem, so I hacked my way around it by adding a custom converter to my ajax call. So I now have this:
$.ajax({
url: this.serviceURL + parameters,
dataType: 'json',
success: callback,
timeout: 3000,
converters: { "text json": HackyJSONConverter },
error: function (jqXHR, status, errorThrown) {
if (status == "timeout") {
//alert("Timed out");
error("The connection to the server timed out.\nEither the server is down or the network is slow.\nPlease try again later.");
}
else {
error("An error occurred while trying to communicate with the server.\n " + errorThrown);
}
}
});
And my hacky converter looks like this:
function HackyJSONConverter(data) {
if (data[0] = 65279) {
// leading BOM - happens only with an iFrame in OT for some unknown reason
data = data.substring(1);
}
return JSON.parse(data);
}
It's immensely stupid, and I would be delighted if anybody has a better way!

Categories

Resources