It’s incredibly simple to build AJAX functionality using the JavaScript jQuery library. The jQuery library provides tons of easy-to-use functionality which enables you to integrate new, awesome features insanely fast. Let’s take a look at how to create a simple AJAX cll with jQuery.
Params
Start out with specifying query params:
- type (post/get…)
- url (target addresse for the AJAX request)
- data (to be sent with the request, e.g. as get params.
- dataType (the expected dataType of the return)
- success (callback method if the AJAX request gets a return)
- error (callback method if the AJAX request fails)
- complete (callback method, running no matter if the request fails or not)
Example
$.ajax({ type: 'get', url: 'some url', data: 'some data', dataType: 'json', success: function(responseText, statusText, XMLHttpRequest) { // Do something with the response on success... }, error: function(XMLHttpRequest, statusText, errorThrown) { // Do something with the response on error... }, complete: function(XMLHttpRequest, statusText) { // Do something with the response no matter the result... console.log(XMLHttpRequest); }, });
In this case the use the normal $.ajax method, which provides what we need.
Move on
So how can you use this? Well, you can trigger AJAX calls on any type of event, for example a mouse-click, and then you can do something with the return value inside the callback methods. For example update a part of a page. A typical example is a “delete” button. Clicking the delete button triggers an AJAX call to the server, the server removes the item from the database, and sends an “ok, item deleted” back. Inside the success-callback, you could then have some jQuery to manipulate the DOM and remove the item representation (for example a table row).
No comments yet (leave a comment)