Debugging AJAX

I can debug my JavaScript using console.log(), which also displays code errors. I can debug my PHP code using print_r() (which I prefer because it’s leaner; many use var_dump()). Since I have PHP’s display_errors directive enabled, and usually I declare error_reporting( E_ALL ^ E_STRICT ) or error_reporting( -1 ), so errors are output within the browser.*

So I can immediately read all my errors and diagnostics, and fix / adjust quickly.

But what about AJAX calls? I can try to limp along by console.logging all the server-side responses, and sifting through to find the appropriate output. If I’m outputting JSON I have to be careful not to mess up that formatting when I dump a variable’s contents for diagnostics.

Thanks to a couple of Linux utilities, I can keep a Terminal / commandline window open, and view all errors and diagnostics therein, right away. (Check to see if your local Linux has these; also the commandline flags may vary.)

Tail
The first is tail. Using this one, I can log all my errors and output my diagnostics to a single file; tail displays them immediately:

tail -f some_dir/console.txt

Using this technique, all my output is tracked in a file so I can refer to it later. Here’s the PHP portion (assume I’m building a class that’s instantiated as a variable $SomeObject):

function __construct() {
	$this->error_logfile = dirname( __FILE__ ) . '/some_dir/console.txt';
	ini_set( 'log_errors', 1 );
	ini_set( 'display_errors', 0 );
	ini_set( 'error_log', $this->error_logfile );
	// et cetera ...
}

public function debug( $data ) {
	file_put_contents( $this->error_logfile, print_r( $data, 1) . PHP_EOL, FILE_APPEND );
}

You’ll need to be sure some_dir/console.txt is a writeable file, or some_dir is a writeable directory.

Within $SomeObject, you can simply output diagnostics anywhere, using

$this->debug( $some_data );

or outside it using

$SomeObject->debug( $some_data );

NC
The second utility, nc, doesn’t output code errors. It “listens” on a particular port number (e.g. 9999) and echoes whatever it “hears.” Unfortunately, it’s not possible to “log” errors to a socket.

nc -lk 127.0.0.1 9999

(Substitute your local IP or simply localhost. Also, check to see if the -k flag indeed means ‘continuous’ in your local version of NC.)

The PHP code outputs (only diagnostics) to that port:

public function debug( $data ) {
	$fp = @fsockopen( "127.0.0.1", 9999 );
	if ( ! $fp ) return;
	fwrite( $fp, print_r( $data, 1 ) . PHP_EOL );
	fclose( $fp );
}

The socket only opens if you’ve first invoked nc to listen on that port, otherwise the method simply returns. Again, you can output diagnostics anywhere using

$this->debug( $some_data );

or

$SomeObject->debug( $some_data );

*Note: this is only a development setting! In production, display_errors should be disabled and log_errors should be enabled.