The code below is pretty standard Drupal code. It sets up a couple of menu items, and a couple of pages. One page displays a link “Click to load” and upon clicking on that link you are taken to a page that has a list of links to some common search engines. Pretty straight forward.
Now, what if I wanted to load the search engine links page via AJAX, and append them to the current page? It’s actually really simple, and it doesn’t involve much additional code either. Lets take a look. All I need to do is make a few changes. The first thing we want to do is alter the landing page code, which will make it look like this.
The first thing I have done here is added misc/ajax.js to the page. This will ensure that the library is included.
Secondly I have added a /nojs/ to the end of the link URI. This is a special property that the AJAX library uses when sending requests, it will be replaced with /ajax/ when making ajax requests. This value is also passed to the page callback so we know how the request was made. We'll look at that function in a second.
You'll see I have also added a CSS class to the link. use-ajax. This tells Drupal to use ajax. When this class is added, Drupal will request the URL of the link with AJAX.
I tacked on a <div id="target"></div> after the link. This is where we want to put the results from our AJAX request.
We have to make some changes to the page callback we are requesting too. Let's now take a look those changes.
After that you'll see that I build a commands array and add the result of ajax_command_replace('#target', $content) to it. What I am doing here is telling Drupal that I want to run the ajax replace command, '#target' is the css selector of what I want to replace and $content contains the HTML I want to replace it with.
At this point I could also add any number of the pre-defined Drupal AJAX commands to the commands array, or even some custom commands I'd defined myself. However for the purpose of this tutorial, we'll keep it simple
The last thing we do is make a call to ajax_deliver(). This renders the response as a valid JSON/AJAX response. From that point the Drupal AJAX library handles the rest.
Now when we click the link we get the Drupal AJAX spinner and then the page is updated with the list of search engines. It’s as easy as that.