SilabGarza - RS Private Server  
Home Forum Play Register Store Market Highscores Mark Forums Read
Go Back   SilabGarza - RS Private Server > SilGar Media > Computers > Programming
Reload this Page [JS/jQuery] Implementing AJAX into your website


[JS/jQuery] Implementing AJAX into your website
Old
  (#1 (permalink))
Evolution is Offline
Also known as Anthony`
image
 
Evolution's Avatar
 
Posts: 43
Cookies Given: 0
Cookies Received: 0
Time Online: 2 h 50 m
   
Lightbulb [JS/jQuery] Implementing AJAX into your website - 08-29-2010, 11:25 AM

Welcome to another tutorial of mine, this one today will focus on implementing AJAX into your webpages. This tutorial assumes you of having basic knowledge of Javascript or jQuery.

Asynchronous Javascript And XML, isnt a relatively new technology. As a matter of fact, the way people invoke AJAX have been in browsers for such an early time, its the way developers use these objects that makes AJAX seem so new. The way AJAX happens to achieve instant dynamic changes to webpages is that it communicates to the web server differently. When the XMLHttpRequest()/ActiveXObject() is invoked and all steps are done, basically the send() method sends a request to the web server, the server then sends its request back with the retrieved data, the same way when the browser retrieves your pages. Here is a simple model to help clear up confusion,


In a nutshell, this is the same way browsers retrieve your pages from any internet link, however it is different of course. Oh I almost forgot.. AJAX ISNT A LANGUAGE.

Implementing AJAX with regular Javascript

Ok, so you understand the basics on how it works, but now you just want to get writting? No problem! The first thing we are going to make here is a simple button that when pressed, will put the contents of a txt file from the server on the page.
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
 
var request;
 
function initAJAX() {
 
   // For modern browsers such as FF, Safari, etc
   if (window.XMLHttpRequest)
      request = new XMLHttpRequest();
   else // For older IE browsers
      request = new ActiveXObject("Microsoft.XMLHTTP");
 
   request.onreadystatechange = checkAJAX;
   request.open("GET", "ajax.txt", true);
   request.send(null);
}
 
 
function checkAJAX() {
   if (request.readyState == 4 && request.status == 200)
      document.getElementById("output").innerHTML = request.responseText;
}
 
</script>
</head>
<body>
<h1>Your first AJAX app? A common little app.</h1>
<fieldset>
<button type="button" onclick="initAJAX()">Submit</button>
</fieldset>
<br />
<div id="output">
AJAX is cool lols.
</div>
</body>
</html>
 
 
 
  1. We use the initAJAX() function to initiate the AJAX connection. In this function, we first check if the browser the guest is using is a modern browser such as FF, Chrome, etc and if so, we invoke a XMLHttpRequest() object which is how AJAX communicates with the web server. If its a different browser, we use an ActiveXObject(). Which is used in older IE browsers.
  2. We use an event handler to check the state of the request. So we made the request object earlier on, the onreadystatechange is actually an event handler. It checks for a change of states in the request. I will describe these 5 states momentarily. As you can see, it will invoke the checkAJAX() function if a state has changed.
  3. The open() is used to open a specific file on the web server. In this case, we want the ajax.txt file so we can display its contents.
  4. We send the request. We send the request with a null parameter. Later we will discuss more on this method.
  5. The checkAJAX() method is called everytime a state has changed. If the state is 4, and the request is 200 (which means successful), then the output element will change. The responseText property is the contents of that request from the web server. Basically, it has the information from the txt file.
The onreadystatechange is an event handler that checks for a change in the readyState property. ASn event handler is like when a program checks for keyboard input, any sort of input from the user. This property is the state of the request to the web server. These are the 5 states;
  • 0 - Uninitialized
  • 1 - Loading
  • 2 - Loaded
  • 3 - Interactive
  • 4 - Completed
The Completed state is what we want to utilize. Next off we have the open() method. This method is basically the connection to the requested file;
open( request , URL , synchronization );

The request is the protocol that the connection will use. The 3 protocols are GET, POST and REQUEST. The URL in this case is the txt file we want to retrieve. The synchronization parameter determines whether or not the connection should be synchronous or asynchronous. In this example, we want AJAX to handle this seperately, so we set it to true which means asynchronous.





What you also need to know are the HTTP request codes the browser use. Here is a simple list;
  • 200 = Successful
  • 400 = Bad Request
  • 404 = Not Found
  • 408 = Request Timeout
  • 500 = Internal Server Error
HTTP request code 200 is what we need to use here.

With the different protocols used to interact with the web server. GET and POST are most typical. This quoted from W3Schools:

Quote:
GET is simpler and faster than POST, and can be used in most cases.




However, always use POST requests when:
  • A cached file is not an option (update a file or database on the server)
  • Sending a large amount of data to the server (POST has no size limitations)
  • Sending user input (which can contain unknown characters), POST is more robust and secure than GET
With AJAX, you can do many things. In this next example, we are going to utilize a PHP file with AJAX. Get ready to put your thinking caps on, because this may be a bit complex,
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
 
var request;
 
function initAJAX(requestText) {
   // For modern browsers such as FF, Safari, etc
   if (window.XMLHttpRequest)
      request = new XMLHttpRequest();
   else // For older IE browsers
      request = new ActiveXObject("Microsoft.XMLHTTP");
 
   request.onreadystatechange = checkAJAX;
   request.open("GET", "lol.php?username=" + requestText, true);
   request.send(null);
}
 
 
function checkAJAX() {
   if (request.readyState == 4 && request.status == 200)
      document.getElementById("output").innerHTML = request.responseText;
}
 
</script>
</head>
<body>
<h1>Your first AJAX app? A common little app.</h1>
<fieldset>
<form action="">
Username: <input type="text" id="input" />
<input type="button" value="submit" onclick="initAJAX(input.value)" />
</form>
</fieldset>
<br />
<div id="output">
Nothing entered.
</div>
</body>
</html>
The PHP file,
PHP Code:
<?php
   $username 
$_GET['username'];
   echo 
"Hello $username!";
?>
  1. The HTML file is almost the same as before. There are some noticeable differences, but the entire structure is basically the same. Create the object, open a connect, check for events, send to the server.
  2. This time, the open() method has a different URL parameter. Looking at the code, you will see we specified a PHP file with an attatched GET reference to it. The GET variable is username. Look in the PHP file, and you will see the file looks for username which is exactly what we specified in the URL parameter. Also, there is a variable that is appended at the end, I will describe this variable in a moment.
  3. The onclick attribute initiates the AJAX request. Within that attribute, you will see a call to the initAJAX() function. As its single parameter, you will notice there is something a little different here. The input.value property takes whats inside the element with an id of input and retrieves whats inside. Take a slight look above and you will notice there is an input element that represents a textfield with a specified id named input. That is the textfield we were grabbing data from.
Ok, so we have successfully made applications in AJAX. Which is pretty cool if you ask me. Try this out on your server and see how this works. But what if we are wanting to use jQuery instead...?



Utilizing AJAX with jQuery

I find using AJAX with jQuery is hell of a lot easier. jQuery uses a different approach to AJAX, first off, it doesnt require a bunch of steps such as before. jQuery is beginner friendly too, so there is no hassle with worrying about different browsers or events assosciated with AJAX.

First, lets begin with a bare-bone example of AJAX with jQuery.
HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
 
function initAJAX() {
   var username = $("#username").val();
   $.get("lol.php", { "username" : username }, result);
}
 
function result(data, textStatus) {
   $("#output").html(data);
}
 
</script>
</head>
<body>
<h1>Your first AJAX app? A common little app.</h1>
<fieldset>
<input type="text" id="username" />
<button type="button" onclick="initAJAX()">Submit</button>
</fieldset>
<br />
<div id="output">
AJAX is cool lols.
</div>
</body>
</html>
The PHP file,
PHP Code:
<?php
   $username 
$_GET['username'];
   echo 
"Hello $username!";
?>
  1. We include the jQuery lib. This should be common sense.
  2. The initAJAX() function initiates the connection. Instead of a bunch of confusing lines of code, we see one simple function called $.get() (yes there is a period before get). This easy function provides the whole 9 yards in one simple function. The first parameter is the file or program name we want, the next is the variable we are going to use. But hold on, lets focus on that. Looking closely you will notice its in some strange format. Thats called JSON data. One of these days I will get into using JSON, but for now stick with me here. There is a string labelled username, this string represents the variable in the PHP script we are going to use. Look back at the previous PHP script and you will understand what im talking about. Hint,
    PHP Code:
    $username $_GET['username']; 
    Beside that we have a double colon and a username variable. Looking at the variable you will see it grabs the content of the username id (#username), and retrieves its contents using the val() method. Finally, the result() function deals with the data that is sent back to us.
  3. The result() function changes the page dynamically. This function by default must have two parameters: data and textStatus. data is what we need to retrieve the information, while textStatus is just the status of the request in a string. And finally, we change the contenets of #output with the data we received.
Realistically, thats all there is to a simple AJAX connection with jQuery.


Conclusion

And there you have it, using AJAX with both Javascript and jQuery! Do some more research on this wonderful technology and see what you can whip up. Im looking forward to seeing some new AJAX applications.

Questions are comments can be left below.
  
adsense code2.3
Closed Thread

Bookmarks

[JS/jQuery] Implementing AJAX into your website

Programming




Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
adsense2.6
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -7. The time now is 10:36 AM.





Powered by vBulletin® Version 3.8.8
Copyright ©2000 - 2017, vBulletin Solutions, Inc.