Tag Archives: post

jQuery DataTables with Lots of Columns Crashes in IE CodeUnit 16 FEB 2011

If you are using the brilliant jQuery DataTables plugin to present your data in nifty dynamic tables, and are using it in a server-side loading context, you have no doubt encountered the issue when a table with a lot of columns (more than 20) fails to load (in other words stays in “processing” mode) when browsing using Internet Explorer (IE).

Mysteriously enough, it does however work in both Firefox and Chrome.

Although difficult to debug, the issue at hand is actually quite simple – essentially IE’s built-in GET size limit is kicking in at the most inopportune of times, meaning that incomplete JSON is heading back towards your page.

The simple solution is to force DataTables to use POST instead of GET for your server-side table, and to do this you need to add the following to your datatable definition:

$(document).ready(function() {
	$('#example').dataTable( {
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": "server_processing_post.php",
		"fnServerData": function ( sSource, aoData, fnCallback ) {
			$.ajax( {
				"dataType": 'json', 
				"type": "POST", 
				"url": sSource, 
				"data": aoData, 
				"success": fnCallback
			} );
	} );
} );

As you can see from the above, the fnServerData variable allows you to specify the type of the ajax call being used, which means we can now force it to POST and thus eliminate our Internet Explorer large column table problem for good!


Related Link: http://datatables.net/

PHP and Google Charts: Using a POST request when a GET String is too Long CodeUnit 16 JUN 2010

Google Charts is an extremely stable and reliable web-based charting engine that is perfect for dropping into any project where you quickly want to produce some high quality graphs for your end user.

The default way to generate a Google Chart is to simple create a normal image tag and set its source to the Google API script with all the chart options passed along as a GET request string.

Of course, as we all know, there is a limit to the length of a GET string and so the question is raised once you start generating bigger graphs, how do you get around this particular limitation?

Well the answer of course lies in using a POST request instead, and thanks to PHP’s explicit support for POST requestes, this becomes as easy as pie! :)

Swiping the demo code straight from Google’s documentation because I’m too lazy to paste my own development example, you can see that the PHP script which handles the generation is nothing more than a file that pushes through the appropriate image content header (in this case a png) and then makes use of the classic fopen functionality (ensure that remote URL access is enabled on your server) to pull down the generated image from Google’s Chart API, specifically setting a POST stream context to handle the chart parameters stored in the previously created data array.

The final leg of work is then of course to simply reference your PHP script as the src of an image tag on the page you want the actual graph to appear.

PHP Chart Script:

  // Create some random text-encoded data for a line chart.
  header('content-type: image/png');
  $url = 'http://chart.apis.google.com/chart';
  $chd = 't:';
  for ($i = 0; $i < 150; ++$i) {
    $data = rand(0, 100000);
    $chd .= $data . ',';
  $chd = substr($chd, 0, -1);

  // Add data, chart type, chart size, and scale to params.
  $chart = array(
    'cht' => 'lc',
    'chs' => '600x200',
    'chds' => '0,100000',
    'chd' => $chd);

  // Send the request, and print out the returned bytes.
  $context = stream_context_create(
    array('http' => array(
      'method' => 'POST',
      'content' => http_build_query($chart))));
  fpassthru(fopen($url, 'r', false, $context));

HTML Page to Display Chart:

Simple, but remarkably effective and thus clever! :P

Related Link: http://code.google.com/apis/chart/docs/post_requests.html

jQuery Across Domain AJAX Content Loads CodeUnit 16 FEB 2010

While working with jQuery and performing AJAX-driven gets and general content loading, have you ever come across your scripts throwing the following error?

permission denied: jquery xhr.open(type, s.url, s.async);

I annoyingly came across this error for the first time a couple of weeks back and after tracing the error all the way back to the main jQuery library file and reading a bit about the thrown error message in particular, I learned something that makes complete and utter sense:

In order to execute better security, Javascript does not allow for AJAX queries to be directed at a different domain from the one on which the AJAX call was originally made.

Makes complete sense, particularly when you think about all those baddies out there, but horribly inconvenient when you do in fact need to load some data that happens to sit on a different data server to the one you actually use as your main web portal.

So is there a fix to this problem that allows cross domain AJAX loading?

The simple answer is yes – as long as you aren’t averse to essentially creating a mini proxy on your own webserver.

Basically what you do to get around the no cross domain querying rule is to create a script that physically grabs the information from the external domain, to which you then point your AJAX load – in other words your display script is talking to your proxy script (which is perfectly legal), and which is in turn talking to the remote domain – in other words the perfect data chain.

To see what I’m trying to describe in action, take a look at the following:

proxy.php contents:

$diginetcontents = file_get_contents('http://diginet.net/modem_info.php?number=' . stripslashes(trim($_GET['to'])));
echo $diginetcontents;

display.php contents:

$('#panel').text = data;

Breaking the above down, what we have done is create a proxy script in proxy.php which simply grabs what is returned from the page on the diginet.net domain, controlling the input by sending along the GET variable it was passed to the file_get_contents function call. The display.php file would be the one that the user is viewing and this initiates the data get from the diginet.net domain by issuing an AJAX get against our proxy script.

It’s an extra step, but now we have the data we couldn’t previously have gotten using pure jQuery with AJAX.

In other words, tutorial done! ;)

(Note, your web server would need something like file_get_contents or fopen which allows for URL parameters to be enabled for this proxy approach to work.)

jQuery: How to Post a Form’s data with Ajax CodeUnit 11 FEB 2010

Ajax posts (or gets) using jQuery is a pretty simple affair, and so I’m not really going into that with this particular post.

Rather, I want to highlight just how easily one can post all of a form’s various values (housed in textboxes, text areas, selects or even radio buttons) to a specific jQuery ajax function call.

So let us examine the working  example below:

$.post('form_post_handler_script.php',$('#yourform').find(":input").serializeArray(),function (data, textStatus){

As you can see, we are using the nifty jQuery deprecated $.post() function to handle the actual POST push. The first parameter passed to it is the actual processing page the function needs to push the data to. The last parameter is simply the callback function, which is in this case doing nothing other than alerting the result of the ajax call). That leaves the interesting one, the actual data parameter that currently sits slap bang in the middle of that function call.

We can break down what is happening into three steps. Remember the $.post function expects data to be fed to it in the JSON format, which if you look around at examples on the web, is most often simply scripted by hand. However, this time around we’re going to let jQuery do the work for us!

The first part is the initial location of the form object, this time selected using its unique ID, in other words $(‘#yourform’) where yourform is the id of the form. Then we chain on a find(‘:input’) command that grabs all elements obeying the :input selector found within the initial object result. Finally, these are then converted to JSON format using the nifty serializeArray function, in other words completing the initial task of providing the post function with the data in the format it so craves.

And that’s it. Populating your ajax post push with your form’s values couldn’t get any simpler if it tried! :)