Some months back I commited myself to creating some WP Tuts and after a while I've finally got around to getting somrething up on the blog. Today Id like to talk about using Ajax in WP (both back and front end). Im going to tell you a little about how we can put together a basic form, post the form data off to a function and get something useful back. You'll need a basic understanding of PHP and jQuery to get your head around this so I would call this a more intermediate level tut. Lets get started.
So what is AJAX?
AJAX is a great way to create dynamic functionality in your website and in short, lets you update content on the page without having to reload it. For example, MS Office uses this technology when it saves your work every few mins. In order to perform the functions we want, AJAX requires HTML, JS and PHP in order for us to create the following simple tut. In fact in most cases you'll find yourself needing all 3 of these to get your functions to work.
Some examples of what Ive been using it for recently:
- Complex search form on a website. Returns the results without reloading the page.
- Pricing calculator.
- Creating new posts from front end.
- Contact form submissions.
- Sending out emails from the back end of WP.
To give you a better idea of what you can do with the AJAX in WP it basically falls into 3 steps:
- HTML Layout to provide a UI from which you can trigger the action.
- jQuery to get any values from the UI and post them to your function.
- PHP to run your chosen function with any posted values from your jQuery.
- You can then return to your jQuery and HTML with a reponse from your function and edit further.
There are a few tuts out there that suggest you create a plugin for this so Im going to follow suit and do the same so you can download the plugin and use it yourself later.
The plugin is available on GitHub at https://github.com/knoppys/knoppysajaxtut. Feel free to do what you like with it but you'll need to install it for the purpose of this Tut.
Once you have installed it, go ahead and add the shortcode "knoppys" to any page or post and you'll get the following form.
The plugin I created uses AJAX to perform a function, in this case it takes the data from the input and runs that data through a wp_query() function and sends back the results (the value in the input is posted to the posts_per_page parameter of the query). Give it a try, add a number into the box and click fetch. Note that the page will not reload, however you will still see the content change.
The plugin and demo.
Ive commented the code so your better of looking in there rather than me posting code on here.
As a guide:
- Create the HTML Elements (in the .php file withing my shortcode function) - line 32
- Get the value from the field and send it to the PHP function. .js file line 5
- Send it to a PHP function to do some stuff with. .php file line 53
- Get it back and do something with the result. .js file line 33