Timothy's Dev Stuff

A collection of code snippets and other developer things.

Log PHP to the JavaScript Console

I have found a few instances where it was fastest to troubleshoot an issue with PHP on a webpage by logging information to the JavaScript console. I created the following function to be used in PHP files.

/**
 * Log data to the JavaScript console
 * 
 * @param $js_var is the variable you want to log in JS console
 * @param $need_encode takes a boolean value indicating whether the $js_var will need to be passed through json_encode() function: true will pass it, false will not. Default is true.
 */
function js_log( $js_var, $need_encode = true ) {
	if ( $need_encode ) {
		$encoded_var = json_encode( $js_var );
	} else {
		$encoded_var = $js_var;
	}
	try {
		echo '<script type="text/javascript">console.log('.$encoded_var.');</script>';
	} catch (Exception $e) {
		echo '<script type="text/javascript">console.log('.json_encode($e).');</script>';
	}
}
After adding this to your PHP, you can easily log data using the js_log() function. Simply pass unencoded data and it will automatically run json_encode() on the data before logging. Alternately, if the data you want to pass is already encoded, also pass false as an argument.

You can read more about json_encode here: json_encode docs.