AJAX driven applications in concrete5

AJAX driven applications in concrete5

Applications are better when they employ AJAX. concrete5 applications are no exception. What is AJAX, and, how do you implement in concrete5?


Article by Ollie / / Comments / Difficulty 
AJAX driven applications in concrete5

AJAX stands for Asynchronous Javascript and XML. As a mnemonic it's something of a misnomer these days since you'll be working with JSON as often as XML - so that makes it AJAJ, or at the very least, AJAXAJ? ;)

The technology is not new; it comprises a client-side script calling back to the server for data, then updating the page with that data, without the need to refresh the entire page which, before AJAX, was typical of a web application on what is, an inherently stateless 'world wide web'.

It used to be a lot of hard work to do AJAX. When standards were less prevalent, approaches more diverse, and jQuery wasn't there for us, different browsers approached the problem in roughly similar but syntactically different ways.

Fortunately this is 2014. Though browsers still do things a bit differently, the jQuery JavaScript framework has abstracted all the nuances away, so we can dive in and do some AJAX without any more pre-history.

The approach I intend to detail here will work in block and single page views. Our example will be basic.

Getting started

There are three components to an AJAX request. First, there is the request for data itself. In our example this will be inititiated using jQuery and will be made from a page of our concrete5 website, mostly likely from a block view, or a single page view. In both scenarios there's a good chance the file will be called 'view.php', so let's use that.

The second component we need is a server-side PHP script to process our AJAX request. Our simple example is going to return some dummy data based on a single request parameter, but feel free to get your data from a Database or API! We'll need a file to host this script. In concrete5 (at least until version 5.7), this type of processing is usually performed in tools files.

The third component is the routine to handle the returned data and update our webpage, all asynchronously!

Let's set the files up.

In view.php, let's create a simple control using a select element. It'll have two options: Dog and Cat.

$form = Loader::helper('form');
$opts = array('dog' => 'Dog', 'cat' => 'Cat');
echo $form->label('animal', 'Which animal is best?');
echo $form->select('animal', $opts, 'dog');
?>

None of that should be alien to you. We're using concrete5's built-in form helper to build a HTML select box control and assigning options from an array. We're also adding a label element using the same approach.

Next job is to detect when this control changes, capture the value, then send via AJAX to our server-side file. As already said, we're doing this from jQuery. This code needs to go in your view.php file, probably somewhere near the bottom:

<script type="text/javascript">
  $(document).ready(function(){
    $('#animal').on('change', function(e){
      var animal = $(this).val();
      $.ajax({
        url: "<?php echo $uh->getToolsURL('ajaxUpdate');?>?animal=" + escape(animal),
        success: function(response) {
          $('#ajax-content').html(response);
        }
      });
    });
  });
</script>

This section needs a bit more explanation.

Obviously it's javascript and using jQuery. We have an event handler on the select control that fires when that control is changed. When it fires we grab the controls value and store it in the animal variable and start the ajax request.

The line of PHP is the standard concrete5 way to get the URL of a tools file. We pass one parameter animal with the querystring of the request, sending the value of animal variable.

Note, we could also pass this using the data property of the jQuery Ajax call. If you were making any request other than GET (which this is) you would have to send data this way rather than tagging it to the querystring as I have done.

Next, we need a placeholder, into which we can place the content we receive following our AJAX request. We're going to use a simple DIV element. This code also goes in our view.php file.

You're asking how the data gets into this element? If you look at the jQuery routine we wrote previously you can see it has a success element, which passes the AJAX response data to an anonymous function once the AJAX call has returned. It is this function that updates the DIV html.

<div id="ajax-content"></div>

Next I'm going to create our tools file in the /tools directory and I'm going to call it ajaxUpdate.php. In this file I add the following code:

$th = Loader::helper('text');
$animal = $th->sanitize($_REQUEST['animal']); 
echo 'You told us your favorite animal is a "' . $animal . 
     '", so we updated this page with that information using AJAX. Boom!'; 
?>

We're expecting to be sent a request to this page, it could be a POST or GET request, but we're expecting to receive the variable 'animal' with the request. We use concrete5's text helper to clean the input, so nothing nasty can be sent to our script and subsequently processed by it - not so important for this example, but good practice and extremely important is we intended to use the variable to construct a database query.

Once you have all this set up in both files, try it. Choose your favorite animal in the select box, and a text statement should appear on the page without any page reloads. You're doing AJAX!

Join the conversation

comments powered by Disqus