I've been trying to use AJAX within my web application to speed things up. I have two files, readdata.php, which contains the html and ajax request, and data.php which echos out the text information that I need to be asynchronously updated.
Here are the two files:
readdata.php
<!DOCTYPE html>
<html>
<head>
<title>Read Data</title>
<?php
//these two posts are required to access the database and are passed through a submit button from index.php
$rName=$_POST["registration"];
$rowId=$_POST["rowid"];
?>
<script>
function showUser(str) { //mostly copied from online ajax tutorial
if (str=="") {
document.getElementById("txtHint").innerHTML==xmlhttp.responseText;
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","data.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}
</script>
</head>
<body>
<br>
<div id="txtHint"><b>data.php text will be listed here.</b></div>
</body>
</html>
and the other:
data.php
<?php
echo "Hello World"; //this is the text that I want to be displayed and asynchronously updated.
?>
</body>
</html>
When I go to index.php and click on the button linking to readdata.php, only the text "data.php text will be listed here." is displayed. Any help would be greatly appreciated.
Allright,
I will try to make it as easy as possible.
I always recommend using jQuery (If so, include the latest API or place it on your host)
$.ajax({
type: "POST", //Or even get
url: "read.php",
data: {
//Theese are the variables and their relative values
name: "Brad",
surname: "Pitt"
}
})
.done(function( msg ) {
alert( "Result: " + msg );
});
Whatever will be echoed from read.php, will be shown on the alert. You can call this script by placing it inside a function() {}
like:
function syncWithAjax() {
$.ajax({
type: "POST",
url: "read.php",
data: {
name: "Brad",
surname: "Pitt"
}
})
.done(function( msg ) {
alert( "Result: " + msg );
});
}