Today I will take you through a very basic Ajax example using jQuery. Usually Ajax can be cumbersome to use, but with jQuery it is very simple.
You can view the example from: http://www.learnjquerynow.com/demos/basic_ajax.php. I suggest that you view the source so you can see what the Ajax is doing.
The example will take the text from a text box and display it reversed below the text box as text is entered into it.
To accomplish this we will need to create a listener for the keyup event that will have to fire the Ajax request. The Ajax request will then call back to the basic_ajax.php page which will echo out the string submitted in reverse.
Let’s go over the code to make this Ajax happen:
<script type="text/javascript">
$(document).ready(function() {
$("#input_text").keyup(function(event) {
$.ajax({
url: "basic_ajax.php",
data: "action=get_reverse&word=" + $("#input_text").val(),
success: function(html){
$("#result_text").html(html);
}
});
});
});
</script>
The $.ajax is what sets the entire Ajax request in motion. It takes a hash of options to determine exactly what it should do.
url – Tells the Ajax which script to call out to. In this case we are calling basic_ajax.php. The same script that we are currently using. You may find some debate between using the same script or an alternative one. The choice is really up to you. Let your project dictate what you do.
data – This is the paramaters that would usually go at the end of the url. In this example, we are setting the action to get_reverse and sending a string called word that is pulled from the input_text input box.
success – This takes in a function that has a paramater that is the text that is returned from the Ajax call. This could be anything from JSON, to plain text (like in our example), or even JavaScript (or jQuery) commands. Within this function you will use the data to do what you need it to do. In this example it simply puts the text it received into the result_text span tag.
This was hardly a real world example for how to use Ajax in jQuery, but was designed to show you how you can set up your own in a very simple way to do some pretty cool things within the web browser.





