Tag Archives: ajax

How to Increase Sencha Ext.getStore Timeout behaviour Tips, Tricks and Tutorials 27 NOV 2014

I encountered a problem the other day where my AJAX loaded store kept failing to load when calling the native Ext.getStore() function. Chrome’s handy Developer Tools indicated that the request to the store URL was being cancelled, indicating that the AJAX request was in fact timing out.

However, Sencha’s documentation didn’t make it very apparent as to how to change the Ext.getStore() timeout behaviour, which is why I’m noting it down here in this post.

As it turns out, you can in fact set the timeout value when you define your store, by adding a ‘timeout’ value to the proxy params in your store definition.

As is the norm, the timeout is in milliseconds, meaning that if you want to set a timeout value of 60 seconds, you need to set “timeout: 60000”.

Here is an example store with the extended timeout config value added (hint: it is just after proxy->type:’ajax’):

Ext.define('KineticaDistell.store.survey.SurveyComplete', {
    extend: 'Ext.data.Store',
    alias: 'store.surveyComplete',
    requires: [
    config: {
        autoLoad: false,
        model: 'KineticaDistell.model.survey.Survey',
        storeId: 'SurveyComplete',
        proxy: {
            type: 'ajax',
            timeout: 60000,
            url: touchwork.SERVICE_URL +  '/survey/survey.php',
            reader: {
                type: 'json',
                rootProperty: 'data'
            extraParams: {

Worked a charm for me.

sencha touch logo

PHP: Simple method to get data from a JSON Web Service CodeUnit 12 NOV 2012

A lot of web services provide you with some useful JSON formatted data in exchange for a few parameters or just some love, and this is a particularly simple and easy method to grab some of that JSON goodness for use in your own PHP page.

In order to grab the data, we’ll first create a HTTP stream content where we’ll add the all important X-Request-With = XMLHttpRequest header that is used to identify requests as being AJAX requests. At this point you can add any parameters you wish to hit the web service with by adding them as an associative array and wrapping them in a http_build_query() call for the context content.

The next step is to use the classic file_get_contents (this assumes your apache/PHP allows the use of the function to open URLs) to hit the target URL using the newly created context.

This should work, resulting in a JSON object which you can use PHP’s json_decode function to manipulate.

In action:

$opts = array('http' =>
        'method' => 'POST',
        'header' => "Content-type: application/x-www-form-urlencoded\r\nX-Requested-With: XMLHttpRequest\r\n",
        'content' => http_build_query(array())
$context = stream_context_create($opts);
$result = file_get_contents("http://webservice.org/route/list/key/mykey/format/json", false, $context);
$jsondata = json_decode($result, true);


PHP: How to traverse through a JSON Object CodeUnit 06 NOV 2012

JSON has become just as big as XML in terms of being the format used to transfer data between AJAX driven web services, meaning that as a PHP developer you will no doubt be doing a lot of dealing with JSON objects.

The default way of grabbing JSON data returned by a web service is to call the built in json_decode function which generates what is known as a stdClass. These can be traversed much as you would a normal array using loops:

$jsondatastdclass = json_decode($jsoninput);

foreach ($jsondatastdclass as $object)
  foreach ($object as $property=>$value)
     echo $property." has the value ". $value;

It’s not great, but it does work. However, later version of PHP do allow you to add a second parameter when calling the json_decode function, namely a boolean which then forces the function to return a normal associative array.

In practice:

$jsondataarray = json_decode($jsoninput, true);

echo $jsondataarray['data'][0];

And now you know.

How to allow File Uploads when using jQuery Mobile CodeUnit 16 DEC 2011

With the release of the powerful jQuery Mobile 1.0 framework, it is now becomes possible for pretty much anyone to crank out an uber slick HTML 5 website that looks like a ‘native app’ on just about any mobile device.

However, one of the things that does break on implementation is the trusty old form file upload element, the result of the nifty AJAX-driven page load system that jQuery Mobile uses. (AJAX doesn’t allow file transfers as a security feature).

Luckily for us though, there is a way to re-enable form file uploads with the only sacrifice being the slick page load, which when you think of it, isn’t such a big sacrifice now that you have the ability to launch files up to your web service once more!

In short, what we want to do is instruct the jQuery Mobile framework to not process the form submit event as an AJAX call. To do this, the following “data-ajax” element property needs to be added to your form declaration:

<form method=”POST” enctype=”multipart/form-data” action=”process_update.php” data-ajax=”false”>

Simple as that.

jQuery and AJAX: How To Send All Selected Values from a Multiple Select Box CodeUnit 28 JUN 2010

Multi-select boxes are wonderful creatures in that they provide a particularly easy to implement user interface element that provides a great deal of functionality to the end user. Today’s quick code tip looks at how one would send all user’s selections made in a multiple select box to a processing script using a jQuery AJAX call.

First off, let us set up our multi select box:

Right. So now we have our multiple select box and a button on which to act upon. The next step is of course the meat of this quick code tutorial, looking at how to post that selected data along to a handler script using a jQuery AJAX call.

So here goes:

//run on save numbers button clicked
    //only do something if numbers are selected
    if( $('#multiselect :selected').length > 0){
        //build an array of selected values
        var selectednumbers = [];
        $('#multiselect :selected').each(function(i, selected) {
            selectednumbers[i] = $(selected).val();
        //post data to handler script. note the JSON.stringify call
            url: 'my_handler_script.php',
            data: {'selectednumbers':JSON.stringify(selectednumbers)},
            type: 'POST',
            success: function(data) {

The trick here is to remember that you can’t simply call .val() on the select box as that will only return one value and not all selected values. So we first run through the list of all selected values (returned by the handy :selected jQuery selector) and push them into a single data array.

Using the JSON2 library to return a usable JSON string of that array, we then make use of jQuery’s built in AJAX functionality to post our data off to our handler script.

And that’s it, couldn’t be simpler – we have now managed to successfully send off an array of all selected values in a multiple select box to our handler script for consumption! :)

jQuery: Bind an onClick Event to an Item in a DataTables Row CodeUnit 14 MAY 2010

As it has quickly become apparent on this site, my two current favourites in the land of web development is the fantastic jQuery javascript library and the brilliant jQuery-based DataTables plugin that gives you instant dynamic table features applied to any bog standard HTML table.

The problem that I’m solving today arose from my desire to include a positive/negative flagging system to data being displayed in a DataTables view. So in each data row I added a column that contained both a greyed out happy and sad smiley face, on which the user will be able to click in order to color the appropriate face and thus indicate a state for that particular row of data.

The idea is simple enough. Click on the smiley face and the script will then fire off an ajax post to a script handler which will fiddle in the database and return the correct state which in turn changes the image accordingly – pretty standard AJAX stuff in other words.

However, herein lay the problem.

Because the DataTables was being fed through a server-side script, in other words the actual table data is loaded by the DataTables plugin itself, my jQuery function that was supposed to interact with the clicking of a smiley face couldn’t work because the elements it was meant to interact with simply didn’t exist when the page’s initial DOM tree was being loaded.

So how to solve this?

Well the solution obviously lies in binding the newly created elements to my existing click handler function, but the question remains – how exactly does one do this if the table data is being loaded through a jQuery function?

Well the answer lies with the DataTables-provided callback function entitled fnDrawCallback, which is called on every ‘draw’ event – in other words the perfect little hook to attach your jQuery code, which is to interact with the DataTables-loaded DOM data, to.

So how does one use this callback functionality then? Well the magic all gets stuffed into the DataTables constructor function. First, we declare the function that is to be run on the click event happening. Then, we bind this function to the click event for the desired elements in the standard jQuery manner. And then for the crucial point, this binding is done as part of the fnDrawCallback declaration in your dataTable constructor call.

So let’s see this in action:

//onClick handler function
function flagsmileysadclick()

//DataTables constructor
oTable = $('#commentstable').dataTable({
"bProcessing": true,
"bServerSide": true,
"iDisplayLength": 50,
"bLengthChange": false,
"sAjaxSource": "datatables_comments_list.php",
"sPaginationType": "full_numbers",
"aaSorting": [[ 0, "desc" ]],
"fnDrawCallback": function() {
  //bind the click handler script to the newly created elements held in the table

And that’s actually it. Simple, but effective, and a nice introduction to the handy fnDrawCallback feature of DataTables.

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! :)

jQuery: Load Remote Content into Current Page CodeUnit 27 DEC 2009

The well-established javascript library jQuery comes bundled with a neat little function that handles loading remote content directly into the current page’s DOM model, namely the little Ajax load function.

Using load is particularly easy, simply bind it to the element you wish to apply it to and call it with an URL – that simple!

For example:


will replace the elementtoupdate’s HTML content with that contained in the remote texttoload.html page, all done with a single, simple call.

Of course, you can expand upon this behaviour as the load function comes with two additional optional parameters, the first one being data which allows you to turn the ajax request into a POST request, while the second callback function allows you to perform certain actions once the ajax operation has completed, like fading in the new text for example.

Note, that it is important to pass extra random GET variables to your load URL as Internet Explorer caches loaded files which could of course completely mess with your dynamically generated content. Usually attaching something like the current timestamp at the end of the URL works wonders in this case. (e.g. texttoload.html?rand=20091227100515 should do the trick quite nicely).

The latest trick available to the load function is that of being able to pass along a selector in the load function and thus apply only matching elements in the HTML to load to the page being updated’s DOM. For more information on doing this though, check out the related link below which details the official documentation for the load function.

Related Link: http://docs.jquery.com/Ajax/load