So I'm trying to just alert out my "Hello" from my php file, it's pretty straight forward but it's not working for some reason.
JS
function dynamic()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "hello.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
dynamic();
PHP
<?php
echo "Hello";
?>
HTML
<html>
<head>
<title>Hello</title>
<script src="dynamic.js"></script>
</head>
<body>
test
</body>
</html>
I can't get the alert box to alert my "Hello". It should just come straight from responseText.
You didn't invoke send
method. It sends the request MDN
xmlhttp.send();
If you want to put any data in POST put it in send methods parameter as urlencoded form.
xmlhttp.send("foo=bar&hello=world");
try this:
function dynamic()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "hello.php", true);
xmlhttp.send(null);
}
dynamic();
I think you forgot to send the request:
xmlhttp.send();
try this
xmlhttp.setRequestHeader("Content-type", "text/plain");
or
xmlhttp.setRequestHeader("Content-type", "text/html");
instead of
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
and you have to put
xmlhttp.send(null);
beside the answer, logging in php file is a useful behaviour in similar situations.