Solved

Best way to Debug JQuery

Posted on 2015-02-14
19
144 Views
Last Modified: 2015-02-20
I do most of my work in PHP and do most of my debugging by doing "screen dumps" to see what is being passed, etc.

But when I move into the world of jQuery and "client side" operations (like aJax calls) I'm a little lost as to how to do debugging.

Maybe I'm not doing the PHP debugging correctly, but no matter what I needed a better way to find errors in my jQuery ajax calls.

I am using a PC running windows 8.1 and my scripts are on a LAMP server.

I use Chrome, Internet Explorer or Firefox as my browsers.
0
Comment
Question by:pkonstan1
  • 6
  • 5
  • 4
  • +2
19 Comments
 
LVL 13

Expert Comment

by:NUKIT
ID: 40610053
I would use Firefox and the plugin Firebug.

That will allow you to see run-time errors as you are working through your jQuery projects.  It also has a nice feature that shows you the AJAX fields and contents it's sending to the server and receiving.
0
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 40610054
In Firefox and in Chrome you can install Firebug (the one for Chrome is a porting). With Firebug you can use console to see error message or to display your own message from jquery code.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40610216
Chrome Dev Tools are your friend.  You can use console.log() to write data elements to the log which can be visualized in the console.  Some learning resources.
https://developer.chrome.com/devtools
http://discover-devtools.codeschool.com/
https://www.codeschool.com/courses/discover-devtools

I also find Firebug helpful, but I never do anything with javascript unless I have Chrome Dev Tools installed and the console open beside my browser window.
0
 

Author Comment

by:pkonstan1
ID: 40610229
This is helpful. I've looked at the Firebug before but what I can't figure out is how to view the actions within the called ajax.php script.

for instance here's a portion of thejQuery code:

var data = $(this).parents("form").eq(0).serialize();
			$.ajax({
				url:"runajax.php",
				data:data+ "&type=checkvalve",
				type:"POST",
				dataType:"JSON",
				success: function(rs){
					if(rs.success){

Open in new window


This script makes an ajax call (to "runajax.php") where it uses php to performs a lookup of a value. if the value is there, it returns a success and the script moves on.

If I place a breakpoint on the "success:function line, the script stops and I can begin stepping through it. But after 20 to 30 presses, I'm still stepping through the jQuery.min.js... script. What I really need to step through is runajax.php steps.

Is there a way to see the actions of the runajax.php script? That's where I'm having a problem.



If I place a breakpoint on the success:function line and then step through it line by
0
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 40610236
No, you can't debug php that way because the code is executed server side. But in the console you can see the results returned by the php script. You can arrange the script in order to get specific messages as return values, using try-catch blocks or just using if-else blocks.
Then, in your success and error functions you can just display those messages

			$.ajax({
				url:"runajax.php",
				data:data+ "&type=checkvalve",
				type:"POST",
				dataType:"JSON",
				success: function(rs){
                                   console.log(rs);

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40610240
That's what console.log() is for!  Drop it into your own code (you don't really benefit from breakpoints in the jQuery source).  It will let you see the flow of your logic and the contents of your variables.  Here's a rough example based on your recent code snippet.

var data = $(this).parents("form").eq(0).serialize();
console.log(data);
			$.ajax({
				url:"runajax.php",
				data:data+ "&type=checkvalve",
				type:"POST",
				dataType:"JSON",
				success: function(rs){
console.log(rs);
					if(rs.success){

Open in new window

Think of it as being like alert() but without interrupting the flow of the program.
0
 
LVL 44

Expert Comment

by:Rainer Jeschor
ID: 40610257
Hi,
in this case I do not fully agree with Ray because you will loose some viable functionality like watches etc.
I use a combo of both.
The console.log BUT then setting the breakpoint exactly on this line.
This enables me in Chrome in the developer extensions to fully get the local variables, add watches ... without worrying about the jQuery code which runs on the success (or failure).
I use also a lot the network tracing of Chrome to exactly see the sent and retrieved headers and streams to easily identify e.g. a wrong parameter or format.
When I need both in parallel, I use Fiddler as proxy (so having two windows to work with).
Just my 2ct
Rainer
0
 
LVL 13

Assisted Solution

by:NUKIT
NUKIT earned 150 total points
ID: 40610261
And start small.  Try checking to see if you even receive a message at all from your PHP page.  Do a sample hello world echo and then alert it upon success.  If you get that, then you can slowly begin to string the rest together and echo back different results to see your code working or failing.

Here's the part in Firebug where you can read the sent items and it's response.  Here's my response is a simple int(0).

Post
Response
0
 

Author Comment

by:pkonstan1
ID: 40610290
These are all helpful things to see what's on the "client" side which is great and is helpful to see what's being sent to the server side.

So what is the best way to see what's happening on the server side.

For example, I had an error in a MySQL query in the runajax.php script. So the script never returned a "success" and it just stopped running.

So what is the best way to discover and find out what is causing the MySQL error. What I ended up doing was setting up a small function that just sent various values (kind of like breakpoints) to a database table as a string (e.g. query values, post variables, etc.) so I could see what was going on and eventually find the error. But these just seems complicated to have to always go to a database just to see what's going on.

Any other suggestions for how to debug the server side ajax.php script?

I like Nukit's encouragement to "start small" and that's in essence what I end up doing. But it always involves multiple steps of having to reload, view a table, fix something, then reload again, etc.  But there may be no way around that.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points
ID: 40610299
The best way to see what is happening on the server side is to debug the server side code separately.  You can use tools like phpUnit to help with the testing on the server.  PhpUnit allows you to "mock" the behaviors of parts of your script.  In fact, you can mock the entire script.  This will produce a perfectly predictable response from any part of the script (like the database abstraction layer) or even from the whole script.  Once you have the code covered with phpUnit, you can be reasonably sure that you're getting something predictable on the server side of things.

MySQL has error reporting functions.  If you use error_log() and / or trigger_error() PHP will record the errors and you can inspect these on the server.  It's relatively easy to write a script that will show you all of the error log files in all of the directories of your server.  After a test - just run it from your web root directory and see if / where any errors showed up.

<?php // find_error_log.php
error_reporting(E_ALL);
ob_start();

// PUT THIS SCRIPT IN THE WEB ROOT DIRECTORY
$path = realpath(getcwd());
$plen = strlen($path);

// THE ERROR LOG FILE NAME
$signal = strrev('error_log');


// IF THERE IS A POST-METHOD REQUEST TO DELETE THIS ERROR LOG
if (!empty($_POST['log']))
{
    // MAKE SURE WE ONLY UNLINK THE ERROR LOG FILE
    $test = strrev($_POST['log']);
    if (strpos($test, $signal) === 0)
    {
        unlink($path . $_POST['log']);
        echo '<h3>' . $_POST['log'] . ' Discarded</h3>';
    }
}


// SEE http://php.net/manual/en/class.recursivedirectoryiterator.php#85805
$objs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

// UNFORTUNATELY THIS DOES NOT WORK AT PHP 5.4
// var_dump($objs);

// ITERATE OVER THE OBJECTS
foreach($objs as $name => $obj)
{
    // PROCESS THE ERROR LOG ONLY
    $test = strrev($name);
    if (strpos($test, $signal) === 0)
    {
        $name = substr($name, $plen);
        $form = <<<EOD
<form method="post" style="margin:0; padding:0; display:inline;!important">
<b>$name</b>
<input type="submit" value="Discard?" />
<input type="hidden" name="log" value="$name" />
</form>
EOD;
        echo $form;

        // SHOW THE CONTENTS OF THE ERROR LOG
        echo '<pre>';
        print_r(file_get_contents($path . $name));
        echo '</pre>' . PHP_EOL;
    }
}

$out = ob_get_contents();
if (empty($out)) echo '<h3>Good News! No error_log found.</h3>';

Open in new window

HTH, ~Ray
0
 
LVL 13

Expert Comment

by:NUKIT
ID: 40610300
Correct, at times there is no way around it.  During your MySQL query did you append an error string on the end?
0
 

Author Comment

by:pkonstan1
ID: 40610313
Appending the error string is something I normally do not do. Can you give me an example of how you would normally do that?
0
 
LVL 13

Expert Comment

by:NUKIT
ID: 40610349
Here's an example packaged up for you in a zip file.  You can see in the getMonstersBirthDate.php file how I send back information upon success or failure of the mysql query.  This is just one example...
phpProjects.zip
0
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 40610563
To debug php you can also install in Firefox the extension FirePhp. You can find it at this page of Firefox addons; https://addons.mozilla.org/it/firefox/addon/firephp/

Once you have installed, you can just put in your php script messages like this:

<?php
function doSomething()
{
    if (this)
    {
        FB::log('this is true');
    }
    else
    {
        FB::warn('this is false');
    }
}
?>
All thse messages will be printed in the Firebug console without interfere with the script flow and they will give you useful information about where problems are.
0
 
LVL 30

Accepted Solution

by:
Marco Gasi earned 250 total points
ID: 40610649
Some more detail I forgot to say.

1 - In order to use FirePhp, you must install Firebug 1.12.8b1: all superior versions miss the FirePhp support (for reasons I just can't understand).
2 - Once you have installed the right version of Firebug, you can install FirePhp from the link provided above.
3 - Now, as explained in the page will show up after the Firefox restart, you have to install a library: you can ownload it directly from here: http://www.firephp.org/DownloadRelease/FirePHPLibrary-FirePHPCore-0.3.2.
You just have to copy the directory contained in the archive in the same directory of the php script which ajax call points to.
4 - In the php script you want to debug you have to add this:
require_once('FirePHPCore-0.3.2/lib/FirePHPCore/FirePHP.class.php');
require_once('FirePHPCore-0.3.2/lib/FirePHPCore/fb.php');
$firephp = FirePHP::getInstance(true);

Open in new window

5 - In the same script you can now put FB::log statements (or info, warn, error) where you need to get some feedback in the console.
I find it an invaluable tool to write ajax/php calls.
0
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 40611371
Oh, I've just discovered that you can use FirePhp even with latest version of Firebug: the icon is not shown, but FirePhp works fine and  at the right of the Firebug icon there is a small space where the FirePhp menu can be open.
0
 

Author Comment

by:pkonstan1
ID: 40611381
Marco,

Thanks for the great suggestions and insights. I'll let this sink in a bit as I try it and will award points in the next couple of days.

Paul
0
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 40611385
No problem for points: take your time :-)
0
 

Author Closing Comment

by:pkonstan1
ID: 40620985
This was one of my most engaged answers. Thanks to all.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now