<script>
try {
function xmldo() {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("para").innerHTML = xmlhttp.responseText;
}
}
var URL = "http:\\127.0.0.1\ajax.php";
xmlhttp.open("GET", URL, true);
xmlhttp.send();
}
} catch (err) {
document.write(err.message);
}
</script>
<p id="para">Hey message will change</p>
<br>
<button type="button" onclick="xmldo()">Click me</button>
This is my code webpage I want to change the content of #para.innerHTML by the respnse in my another php file ajax.php
<?php
$response="hey is text changed";
echo $response;
?>
I am using wamp so i placed my ajax.php in my www folder and set the location of file on server as 127.0.0.1/ajax.php [URL] but i on pressing the button the text at para placeholder is not getting changed. I am new to AJAX so must be missing on some points. Plz help me with them.
Change the slashes in your URL.
You have: http:\\127.0.0.1\ajax.php
but the correct way is: http://127.0.0.1/ajax.php
I would also suggest using jQuery to perform AJAX requests - it's much simpler and you write less code!
I've added an example below written in jQuery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button_id").click(function(){
$.ajax({
url: 'http://127.0.0.1/ajax.php',
cache: false,
type: 'GET',
dataType: 'HTML',
error: function (e){
console.log(e);
},
success: function (response){
$("#para").empty().append(response);
}
});
});
});
</script>
<p id="para">Hey message will change</p><br>
<button type="button" id="button_id">Click me</button>