MENU
AJAX- XMLHttpRequest
The same-origin policy applies to XMLHttpRequests unless the server provides an Access-Control-Allow-Origin (CORS) header.
If you wish to access the session variables in an AJAX call, remember to start the PHP script with: <?php session_start(); ?>
Retrieving a Static File
RESETRUNFULL
<!DOCTYPE html><html><head>
<script>
function loadText(){
var xhr;
xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200)
document.getElementById("myDiv").innerHTML = xhr.responseText;
};
xhr.open("GET","/shared/test.txt",true);
xhr.send();
}
</script>
</head><body>
<div id="myDiv"></div>
<button type="button" onclick="loadText()"> Retrieve Text </button>
</body></html>
Synchronous Transfer using POST
AJAX data is not automatically URL-encoded, unless you use FormData. However, the AJAX data is automatically URL-decoded at the PHP end, so that you can use $_GET, $_POST, and $_REQUEST directly.
RESETRUNFULL
<?php
// /shared/poll.php
$v = $_POST['vote'];
$content = file("poll.txt");
list($yes,$no) = explode("|",$content[0]);
if ($v==0) $no++;
if ($v==1) $yes++;
file_put_contents("poll.txt","$yes|$no");
?>
<h3>No: <?php echo $no; ?> </h3>
<h3>Yes: <?php echo $yes; ?> </h3>
<!DOCTYPE html><html><head>
<script>
function vote(v){
var xhr;
xhr=new XMLHttpRequest();
xhr.open("POST", "/shared/poll.php", false);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("vote="+v);
document.getElementById("poll").innerHTML = xhr.responseText;
}
</script>
</head>
<body>
<div id="poll">
<h3>Do you think AJAX is fun?</h3>
No: <input type="radio" name="vote" value="0" onclick="vote(this.value)"/>
Yes: <input type="radio" name="vote" value="1" onclick="vote(this.value)"/>
</div>
</body></html>
Asynchronous Transfer using GET
Syntactically, an asynchronous transfer may look more complex to the coder. However, it allows the webpage to be responsive. For example, with it, you can display an animated gif while some data is being retrieved.
RESETRUNFULL
<?php
// /shared/gethint.php
$a = ["Paul","Crowe","Betrand","Mary","Irene","Fiona","Gundesen","Hegel","Singa","Johan","Katherine","Jacky","Lina","Opheus","Petronas","Ananda","Racheal","Cindy","Doris","Eva","Livita","Sunny","Trovalta","Inu","Purple","Liza","Alexander","Ellen","Wendy","Vincent"];
$q=$_GET["q"];
if (strlen($q) > 0){
$hint="";
for($i=0; $i<count($a); $i++){
if (stripos($a[$i],$q)) {
$hint = ($hint=="")?$a[$i]:$hint." , ".$a[$i];
}
}
}
echo ($hint=="") ? "no suggestion" : $hint;
?>
<!DOCTYPE html><html><head>
<script>
function showHint(s){
var xhr;
if (s.length==0){
document.getElementById("hints").innerHTML="";
return;
}
xhr=new XMLHttpRequest();
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200)
document.getElementById("hints").innerHTML = xhr.responseText;
}
xhr.open("GET","/shared/gethint.php?q="+s+"&r="+Math.random(),true);
xhr.send();
}
</script>
</head><body>
<h3>Start typing a name:</h3>
Name:
<input type="text" onkeyup="showHint(this.value)" />
<p>Suggestions: <span id="hints"></span></p>
</body></html>
Upload Progress and FormData
This example is for illustration only. 'upload.php' does not exist in our server.
RESETRUNFULL
<?php // upload.php
move_uploaded_file($_FILES["upload_file"]["tmp_name"],
$_FILES["upload_file"]["name"]);
echo "input_text1: ".$_REQUEST["input_text1"]."<br/>";
echo "input_text2: ".$_REQUEST["input_text2"]."<br/>";
//echo "secret: ".$_REQUEST["secret"];
?>
<!DOCTYPE html><html><head>
<script>
var start_time;
function start_upload() {
d=new Date();
start_time=d.getTime();
f = document.getElementById("file_uploader").files[0];
if (f.size > 100*1024*1024){
document.getElementById("msg").innerHTML = "file too large";
return;
}
if (f.name.substr(-4,4)!=".exe"){
document.getElementById("msg").innerHTML = "invalid type";
return;
}
fd = new FormData(document.getElementById('upload_form'));
fd.append("input_text2","===&&&===");
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', upload_progress, false);
xhr.addEventListener('load', upload_finish, false);
xhr.addEventListener('error', upload_error, false);
xhr.open('POST', '/upload.php');
xhr.send(fd);
}
function upload_progress(e) {
if (!e.lengthComputable) return;
p = e.loaded * 100 / e.total;
p = p.toFixed(3);
d = new Date();
r = e.loaded/((d.getTime()-start_time)/1000)/1024;
r = r.toFixed(3);
document.getElementById("msg").innerHTML = p+"% completed.<br/>rate: "+r+"KB/s.<br/>";
}
function upload_finish(e) {
document.getElementById("msg").innerHTML += e.target.responseText;
}
function upload_error(e){
document.getElementById("msg").innerHTML = "Upload error.";
}
</script>
</head>
<body>
<form id="upload_form">
<input type="hidden" name="secret" value="~!@#$%^&*()_+ "/>
<input type="text" name="input_text1"/><br/>
<input type="file" name="upload_file" id="file_uploader"/>
</form>
<button onclick="start_upload();">Upload</button>
<p id="msg">Please upload an .exe file.</p>
</body></html>