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>';
}
}
You can read more about json_encode here: json_encode docs.