ajax call to php not working properly
i'm making an ajax call to a php function... i'm trying to display the server time on the time input field using a php script... i was following a tutorial i found online word per word but for some reason i keep receiving the actual text from the php file in time input field... can someone please tell me why this is happening?
here's my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Server Time Example</title>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
开发者_运维问答 ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "serverTime.php", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
Here's the PHP:
<?php
echo date("H:i:s");
?>
I'm going to make the assumption you are using Apache as your web server. You should ensure you have something similar to the following in your configuration:
AddType application/x-httpd-php .php
It looks like your files are being served as plain text instead of being handed off to PHP.
Check the following:
- The php code (
echo date("H:i:s");
) should be in a separate file from the ajax/html code (technically there are ways to get around this, but they make everything much more complicated) - The php file should have the
.php
extension - Your server should be configured to treat the
.php
file extension as php code (see Ek0nomik's answer) - The php code should have
<?php
and?>
tags around it - Your server should have php installed
If all this fails, go to the php file directly in your browser and see what comes up.
I'm going to play Carnac and say it's because you don't have <?PHP
at the beginning of your file and ?>
at the end of your file.
精彩评论