AJAX Made Easy!

AJAX is an amazing technology in it’s own right, and as it’s natively a piece of javaScript functionality it bolts straight in to a javaScript-enabled WordPress.

AJAX allows Asynchronous Javascript And XML. XML is a markup allowing data to be transported, although thats not the only format AJAX will work with.

If you’ve got the jQuery & javaScript plugin installed you should be able to use AJAX.

AJAX USING LOAD

$.load() is just one of a number of methods we can use which employs AJAX. We create a DIV on our page to receive data we pull in from our own or an external website.

<div id="loadOutput"></div>

Then we use javaScript (or in this case jQuery) to load something into that DIV.  In this instance I’m loading a DIV with an id of ‘onlyTheseWords’ from a page called ‘words.html’ at a site called ‘http://individ.co.uk’.

var words = 'http://individ.co.uk/words.html #onlyTheseWords' ;
$('#loadOutput').load(words) ;
console.log(words) ;

As you can see in the example above I’ve also sent the returned data to console.log() – when I view my developer console I can see the success or failure of this AJAX call.

USING RAW AJAX

You can achieve similar results with a raw AJAX call. The $.ajax() command offers a whole lot more than just loading something from a page. We can pass parameters to an external script, have that script do something, and return the results to our AJAX call.
First, let’s have another DIV ready to accept some data …

<div id="scriptOutput"></div>

Now we have a bit of jQuery which includes an AJAX call to our server.

$.ajax({
   url: 'http://individ.co.uk/myScript.php' ,
   type: 'GET',
   success: function(data) {
      console.log(data) ;
      $('#ajaxOutput').html("myScript.php says " + data) ;
   }
})

Our PHP script at http://individ.co.uk/myScript.php just echos the word ‘HELLO’ – but that’s enough to show our AJAX call is working.

THAT’S IT!

Yeah, I know, that script isn’t doing anything at all useful, but it does demonstrate how easy it is to use AJAX to get information from external sites.

In other posts I’ll explore how to make use of AJAX in many other situations.

Till then, nJoy!

Share

You may also like...

1 Response

  1. charliecat says:

    I was struggling with a bit of code like this but could not get it to work I was missing the bit with the div but now it works, thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *