The Black Hole Layer of Websites

By ryan, January 21, 2015

When coding websites there are 2 basic ways to make a website dynamic:

  • Javascript
  • Sever Side

Many sites use both at the same time… this is a layer that gets difficult to debug.

Many times developers get used to working in one or the other — and the point where they meet becomes a confusing mess…
Let me demonstrate:

 
jQuery(document).ready(function(){
    jQuery('#my_button').on('click', function(){
        transport = {
            "banner_instance":jQuery(this).attr('banner')
        }
        jQuery.ajax({ 
            type:"POST",
            url:'/webservice/banners', 
            data: transport,
            dataType:"json",
            success: function(data){
                jQuery('#results').html('');
                html = '';
                if(data.code == 1){
                    jQuery.each(data, function(key,banner){
                        html += '<div id="banner-item-'+banner.id+'">';
                        html += '<img src="'+banner.src+'"><br>';
                        html += '<h3>'+banner.titile+'</h3>';
                        html += '<p>'+banner.caption+'</p>';
                        html += '</div>';
                    }
                }else{
                    html = '<span class="message">'+data.message+'</span>';
                }
                jQuery('#results').html(html);
            }
        });
    });
});

And here is an example of the file that the AJAX method is calling:

<?php
class Transport{
	public $code;
	public $message;
	public $data;
}
$transport = new Transport;
if(mysql_connect('localhost', 'mysql_user', 'mysql_password')){
	$query = 'SELECT * FROM my_banners WEHRE banner_instance = '.$_POST['banner_instance'];
	$result = mysql_query($query);
	if(mysql_num_rows($result) <= 0) {
		$transport->code = 0;
		$transport->message = 'No Results';
	}else {
		$transport->code = 1;
	}
	while ($row = mysql_fetch_object($result)) {
	  $transport->data[] = $row;
	}
}else{
	$transport->code = 0;
	$transport->message = 'Cannot Connect to Database';
}
echo json_encode($transport);
?>

Now – lets assume there is a banner missing… How do you begin debugging it? Myself – I would test the XHR endpoint either manually or by the Network tab in Developer Tools (or Firebug). Ensure that the JSON object has the data. If not, then its the webservice or the database. Otherwise you will need to view each banner object to ensure a character is not invalid or other things that could go wrong when working in the Javascript world. The issue may also be CSS or HTML (however the HTML issue is much less common)

This is a simple example of how working with both server side and Javascript can make seemingly simple debugging much more complicated that you may have intended