AJAX is used for loading content.
Why should you use AJAX?
AJAX can be used to…
- Load PHP without reloading the page
Notes:
- Do not use AJAX repeatedly. This could get you suspended on InfinityFree.
Methods and Attributes
First, you will need a JavaScript XMLHTTPRequest
object.
<script>
var myReq = new XMLHTTPRequest(); // This is an object.
</script>
Here is a list of the methods and attributes.
Methods | Defined |
---|---|
open(method, url, a) |
method is for the way you would send the request, either "GET" or "POST". POST is sent through the send() method and GET is set through the URL . You could also use both. a is "true" if you want it to load with the other content and "false" if you must load it before the content. true is better. |
setRequestHeader(name, value) | Sets the header for the URL. name is the name of the header and value sets the value. |
getResponseHeader(name) | Gets the content of the response header. |
abort() | Stops the entire request from happening. |
getAllResponseHeaders() | Gets all response headers as a string. |
Attributes | Defined |
---|---|
onreadystatechange | The function to be used when the ready state changes. |
readyState | The ready state, i.e., 4 - Finished, or 3, 2, or 1. |
status | The status, i.e., 200 (Ok), 404 (Not Found). |
statusText | The status text, like Ok (200) or Not Found (404) |
responseHTML | The HTML received |
responseXML | The XML received |
Setup
You need JavaScript.
Name this file ajax.js
:
function myTime() {
// Stop the browser from caching the request
var myRand = Math.random();
myReq.open("GET", "time.php?rand=" + myRand, true);
myReq.onreadystatechange = function() {
if (myReq.status == 200 && myReq.readyState == 4) {
var result = myReq.responseText;
var content = document.getElementsById('content');
content.innerHTML = result;
}
}
myReq.send();
}
Name this file time.php
<?php
/* Replace with format date */
echo date(); # optional
?>
Name this file index.html
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Verdana;
}
#content {
padding: 5px;
border: solid black 2px;
width: 100%;
height: 200px;
}
</style>
<script src="ajax.js"></script>
<script>
var myReq = new XMLHttpRequest();
</script>
</head>
<body>
Getting the time: <button onClick="myTime();">Get Time</button>
<div id="content"></div>
</body>
</html>
In the example above, you only need to get the time by pressing the button.
How about POST data?
If you are using POST data, then you would need:
<script>
var params = "item=6¬hing=false";
myReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myReq.setRequestHeader("Content-length", params.length);
myReq.setRequestHeader("Connection", "close");
myReq.send(params);
</script>
Hope this helps with AJAX!