I've just read through some tutorials on using ajax with rails. Below you can see a JS script extracted from one of them with some modifications which I expected to cause some errors and write some text somewhere. (public/javascripts/application.js)
$('.submittable').live('change', function() {
$(this).parents('form:first').submit();
fdafdasfewa
document.write("Welcome to my world!!!");
echo "------------------";
});
In fact the script still works with no side effects.
Where does document.write and echo put text?
How can I debug such a script when I can't even see its output? Well sometimes probably I'll not even be able to determine if ran or not.
Try putting in an alert to make sure your code is being reached
$('.submittable').live('change', function() {
$(this).parents('form:first').submit();
alert('reached this point');
...
Also, use Firebug or Chrome's development tools. In Chrome on the mac the shortcut is command-alt-i to bring up the dev tools, then click 'console' to bring up...the console.
In the console you can type
$('.submittable')
To make sure your js has a dom element to attach to. If $('.submittable') returns nothing then there's no dom element selected. You can even set breakpoints and step through them in the dev tools. To create a break point just do
$('.submittable').live('change', function() {
$(this).parents('form:first').submit();
debugger;
...
and the dev tools will take over when that line is reached.
My guess is when you called the $(this).parents('form:first').submit() the page posted the form and javascript didn't execute past that point, which is why it didn't throw any errors of or write anything to the document.
I would use console.log to write test output in combination with the developer tools in chrome or Firebug. That way you know to look in the console and you can also use things like breakpoints to watch the execution of the javascript.
Related
I made a function called test() in javascript file.Placed a simple alert into it.
In html file, called the method on click of a button. But,it was not being invoked.
Problem was in the 11th function, nowhere related to mine !!!! But, how can a person making his first javascript function suppose to find that out ???
I am looking for best ways to debug javascript.
You can debug javascript using many modern browsers. See this question for details on how to debug in Google Chrome:
How do you launch the JavaScript debugger in Google Chrome?
Furthermore, you shouldn't use alert() for debugging as this can give different results to a production version due to alert() causing a pause in the script.
It is best practice to use console.log() and view the output in the browsers Console.
You can also put debugger in your javascript code to force a breakpoint. However I prefer not to use this as forgetting to remove this before deployment will cause your script to pause, which can be quite embarrassing!
You should use the debug console provided by the browser.
Chrome has it inbuilt, press CTRL + SHIFT + j. In Firefox, install Firebug plugin.
In your code, add alert() to show flow and get values of variables.
Also, use console.log() which will only output to the debug console.
Depending on your browser choice there are debugging options - I tend to use Firefox, so Firebug in my case. There is a question that list options for other browsers - What is console.log and how do I use it?
Unless the project you're working on has already adopted a mechanism for debugging, console.log() tends to be a simple and useful option when tracking down a problem.
Whilst debugging you could take the approach to log out a line when entering a function, like so:
var myFunc = function(el) {
console.log('Inside myFunc');
// Existing code
};
This will enable you to see which functions have been called and give you a rough idea of the order of execution.
You can also use console.log() to show the contents of variables - console.log(el);
Be mindful to remove/disable console.log() calls once you're done as it will likely cause some issues in production.
To answer your question within question,
how can a person making his first javascript function suppose to find that out ???
Well, when something is wrong in JavaScript, for example, you made a syntax error - the script will stop working from there. However, this won't stop HTML from rendering on, so it might look as if everything is correct (especially if your JS is not changing the look of the page) but all the functionality of JS will be dead.
That's why we use the debug tools (listed in the other answers here) to see what's wrong, and in cases like this, it's very easy to notice which function has errors and is causing the whole script to break. This would probably have save a few minutes to your seniors as well.
The best approach would be to test frequently so that whenever you run into errors, you can fix them right away.
I am a chronic user of Firebug, and I frequently need to log various stuff so that I can see what I am doing. The console.log function is a lot to type. Even if I assign it to a single letter variable like q = console.log, I have to do it every time I fire up Firebug. Is there any way to do it such that q always refer to console.log (unless, of course, I override it in my session)?
To answer your question, the functionality doesn't currently exist, however I have found the firebug developers to be very responsive in the past. Why don't you put in a feature request on their forum, or better yet, code it up yourself, and ask them to add it?
Depending on your IDE, simply setup a code snippet (I use Flash Develop, so Tools -> Code Snippets).
I believe this to be a better way than setting up redirect scripts and what not, because it stops the Firebug namespace from being polluted, and makes it easier/more consistent to debug if your debugging breaks down.
The screenshot shows me using Flash Develop, hitting Ctrl+B, then hit enter. The pipe (|) in the snippet indicates where the cursor will be placed to start typing after inserting the snippet.
I want to force the Chrome debugger to break on a line via code, or else using some sort of comment tag such as something like console.break().
You can use debugger; within your code. If the developer console is open, execution will break. It works in firebug as well.
You can also use debug(function), to break when function is called.
Command Line API Reference: debug
Set up a button click listener and call the debugger;
Example
$("#myBtn").click(function() {
debugger;
});
Demo
http://jsfiddle.net/hBCH5/
Resources on debugging in JavaScript
http://www.laurencegellert.com/2012/05/the-three-ways-of-setting-breakpoints-in-javascript/
http://berzniz.com/post/78260747646/5-javascript-debugging-tips-youll-start-using-today
As other have already said, debugger; is the way to go.
I wrote a small script that you can use from the command line in a browser to set and remove breakpoint right before function call:
http://andrijac.github.io/blog/2014/01/31/javascript-breakpoint/
debugger is a reserved keyword by EcmaScript and given optional semantics since ES5
As a result, it can be used not only in Chrome, but also Firefox and Node.js via node debug myscript.js.
The standard says:
Syntax
DebuggerStatement :
debugger ;
Semantics
Evaluating the DebuggerStatement production may allow an implementation to cause a breakpoint when run under a debugger. If a debugger is not present or active this statement has no observable effect.
The production DebuggerStatement : debugger ; is evaluated as follows:
If an implementation defined debugging facility is available and enabled, then
Perform an implementation defined debugging action.
Let result be an implementation defined Completion value.
Else
Let result be (normal, empty, empty).
Return result.
No changes in ES6.
On the "Scripts" tab, go to where your code is. At the left of the line number, click. This will set a breakpoint.
Screenshot:
You will then be able to track your breakpoints within the right tab (as shown in the screenshot).
There are many ways to debug JavaScript code. Following two approaches are widely used to debug JavaScript via code
Using console.log() to print out the values in the browser
console. (This will help you understand the values at certain points
of your code)
Debugger keyword. Add debugger; to the locations you want to
debug, and open the browser's developer console and navigate to the
sources tab.
For more tools and ways in which you debug JavaScript Code, are given in this link by W3School.
It is possible and there are many reasons you might want to do this. For example debugging a javascript infinite loop close to the start of the page loading, that stops the chrome developer toolset (or firebug) from loading correctly.
See section 2 of
http://www.laurencegellert.com/2012/05/the-three-ways-of-setting-breakpoints-in-javascript/
or just add a line containing the word debugger to your code at the required test point.
Breakpoint :-
breakpoint will stop executing, and let you examine JavaScript values.
After examining values, you can resume the execution of code (typically with a play button).
Debugger :-
The debugger; stops the execution of JavaScript, and callsthe debugging function.
The debugger statement suspends execution, but it does not close any files or clear any variables.
Example:-
function checkBuggyStuff() {
debugger; // do buggy stuff to examine.
};
You can set debug(functionName) to debug functions as well.
https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints#function
I wouldn't recommend debugger; if you just want to kill and stop the javascript code, since debugger; will just temporally freeze your javascript code and not stop it permanently.
If you want to properly kill and stop javascript code at your command use the following:
throw new Error("This error message appears because I placed it");
This gist Git pre-commit hook to remove stray debugger statements from your merb project
maybe useful if want to remove debugger breakpoints while commit
How to Debug java Script Error Using Firebug?
Duplicate
How can I set breakpoints in an external JS script in Firebug
Debug using FireBug.
Just check the line on which the error is occuring, then, just before that line, write a "debugger" call.
debugger; //Will invoke FireBug's debugger.
var err = abcs; //Line containing error
To debug an error in firebug :
1- select inspect tab from menu
2- Set break point in the line that
causes error
3- Refrsh the page
4- use F10 to step by step debug and
F5 to end debgging
It's like debgging of visual studio
Use the console.log(yourObject) function to output anything to the firebug console. It is just like running a var_dump and you can view all your objects and their contents. This is very helpful if you want to check on the contents of a particular variable or even a particular DOM object.
Instead of using cheap alerts - the console.log() function is cleaner and you can see all the outputs neatly in your console pane.
Note however you need to remove all references to the console.log function when you deploy your website as it would not run in IE.
you can put breakpoints in the code, and wait for the execution to hit them. Then you can walk in the code, and use watches to know the values of variables.
You can use Firebug, and for debugging in chrome, you can use firebug lite
Why Firebug , try Visual studio , it has a rich debugging features ;)
I have an ASP.NET MVC project that uses some simple AJAX functionality through jQuery's $.get method like so:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
});
The amount of content is relatively low here -- usually a single div with a short blurb of text. Sometimes, however, I am also injecting some javascript into the page. At some point when I dynamically include script into content that was itself dynamically added to the page, the script still runs, but it ceases to be available to the debugger. In VS2008, any breakpoints are ignored, and when I use the "debugger" statement, I get a messagebox saying that "no source code is available at this location." This fails both for the VS2008 debugger and the Firebug debugger in Firefox. I have tried both including the script inline in my dynamic content and also referencing a separate js file from this dynamic content -- both ways seemed to result in script that's unavailable to the debugger.
So, my question is twofold:
Is there any way to help the debugger recognize the existence of this script?
If not, what's the best way to include scripts that are used infrequently and in dynamically generated content in a way that is accessible to the debuggers?
I can not comment yet, but I can maybe help answer. As qwerty said, firefox console can be the way to go. I'd recommend going full bar and getting firebug. It hasn't ever missed code in my 3 years using it.
You could also change the way the injected javascript is added and see if that effects the debugger you're using. (I take it you're using Microsoft's IDE?).
In any case, I find the best way to inject javascript for IE is to put it as an appendChild in the head. In the case that isn't viable, the eval function (I hate using it as much as you do) can be used. Here is my AJAX IE fixer code I use. I use it for safari too since it has similar behavior. If you need that too just change the browser condition check (document.all for IE, Safari is navigator.userAgent.toLowerCase() == 'safari';).
function execajaxscripts(obj){
if(document.all){
var scripts = obj.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
eval(scripts[i].innerHTML);
}
}
}
I've never used jquery, I preferred prototype then dojo but... I take it that it would look something like this:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
execajaxscripts(result);
});
The one problem is, eval debug errors may not be caught since it creates another instance of the interpreter. But it is worth trying.. and otherwise. Use a different debugger :D
This might be a long shot, but I don't have access to IE right now to test.
Try naming the anonymous function, e.g.:
$.get(myUrl, null, function anon_temp1(result) {
$('#myselector').html(result);
});
I'm surprised firebug is not catching the 'debugger' statement. I've never had any problems no matter how complicated the JS including method was
If this is javascript embedded within dynmically generated HTML, I can see where that might be a problem since the debugger would not see it in the initial load. I am surprised that you could put it into a seperate .js file and the debugger still failed to see the function.
It seems you could define a function in a seperate static file, nominally "get_and_show" (or whatever, possibly nested in a namespace of sorts) with a parameter of myUrl, and then call the function from the HTML. Why won't that trip the breakpoint (did you try something like this -- the question is unclear as to whether the reference to the .js in the dynamic HTML was just a func call, or the actual script/load reference as well)? Be sure to first load the external script file from a "hard coded" reference in the HTML file? (view source on roboprogs.com/index.html -- loads .js files, then runs a text insertion func)
We use firebug for debug javascript, profile requests, throw logs, etc.
You can download from http://getfirebug.com/
If firebug don't show your javascript source, post some url to test your example case.
I hope I've been of any help!
If you add // # sourceURL=foo.js to the end of the script that you're injecting then it should show up in the list of scripts in firebug and webkit inspector.
jQuery could be patched to do this automatically, but the ticket was rejected.
Here's a related question: Is possible to debug dynamic loading JavaScript by some debugger like WebKit, FireBug or IE8 Developer Tool?