I started learning AJAX and got problem on the beginning I can't solve. I got 2 files, main.html with code :
<!DOCTYPE html>
<html>
<head>
<title>My page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<button>apple</button>
<div id="target">
Press button
</div>
<script>
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++)
{
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","blabla.txt",false);
xmlhttp.send(null);
document.getElementById("target").innerHTML=xmlhttp.responseText;
}
</script>
</body>
</html>
and "blabla.txt" with content :
asdasdsaldkjasdajsdl
Problem is that after clicking the button it should load content of blabla.txt file into the div element. Unfortunately it doesnt work with the reason i have no idea about.
I think its worthly to add that both files are placed in the same folder.
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("target").innerHTML=xmlhttp.responseText;
}
}
<div id="test"></div>
$(document).ready(function(){
$.get('ajax/test.txt', function(data) {
$('#test').html(data);
});
})
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
var DONE = (xmlhttp.readyState == 4 && xmlhttp.status==200) ;
if (DONE){
document.getElementById("target").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","blabla.txt",false);
xmlhttp.send(null);
Use the above code. You need to add the state of ajax to check ajax is completed or not. otherwise it will execute same time and will not found the response text.