Javascript form & Ajax request to PHP
Why is this not working? When the Ajax code IS NOT wrapped in function xmlhttpGet()
it does work: PHP returns the called page and inserts it into the DIV. In this code i have wrapped the code into the function xmlhttGet() amd nothing happens. The requested page is not loaded into the DIV.
<html><head><title>AJAX GET </title>
</head><body><center />
<h1>Loading a web page into a DIV</h1>
<FORM id="form" method="post" action="">
<b> Enter argument: </b>
<input size="40" name="q" id="q" value="">
<INPUT TYPE="submit" id="submit" VALUE="Submit" onClick="xmlhttpGet(this.form)">
<INPUT TYPE="reset" VALUE="Reset">
</FORM>
<div id='info'>This sentence will be replaced</div>
<script>
function xmlhttpGet(form)
{
nocache = "&nocache=" + Math.random() * 1000000
request = new ajaxRequest()
var $q = form.q.value
request.open("GET", "urlget.php?url=amazon.com/gp/aw" + nocache, true)
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementById('info').innerHTML =
this.responseText
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
}// END xmlhttp开发者_开发知识库Get
request.send(null) ;
function ajaxRequest()
{
try
{
var request = new XMLHttpRequest()
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}// ajaxRequest
</script></body></html>
[EDIT]
the onClick is triggered fine. I have verified by inserting alerts into the functions.
[EDIT2]
i suppose it would help if i show the PHP bit too
<?php // urlget.php
if (isset($_GET['url'])) {
echo file_get_contents("http://".sanitizeString($_GET['url']));
}
else {
echo "problem!" ; // [edited line]
}
function sanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>
you have to call xmlhttpGet()
somewhere in ur script to get it to 'run'
When your code is not wrapped in a function, it will simply execute as the code is parsed by the browser.
Once you wrap it in a function, it will not execute until the function is explicitly called.
If you want to get the script to run automatically, try changing your body tag to:
<body onload='xmlhttpGet();'>
If you want to fire the function with user interaction, use one of the many events such as onclick
or onmouseover
or onmousedown
Your xmlhttpget
function should start as:
function xmlhttpGet(form)
{
... as it is you're referencing the variable form
in the function (eg var $q = form.q.value
) but never assigning it a value (so it's being created/pulled from global scope).
The scope of this
in your function for onreadystatechange
will vary wildly depending on browser and how it's called - not a good design decision, try replacing this
with request
in the function.
精彩评论