Hi all I have to connect to an external server to retrieve data.
They told me to use their script and I have to modify something because it was wrong. Now I ahve a problem when I try to lunch my request.
Return me an error into my internet explorer console
SCRIPT10: The data required for the completion of this operation are
not yet available.
This is my javascript page, the problem I think is because the query doesn't finish in time to print my result. How can I print the result when they are ready and don't return me error?
I have try to comment all my request and leave only the method "open" but the error return me every time. Why??
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
var req = null ;
function sendRequest(){
var urlStr="www.test.it";
var xmlString="";
xmlString+="<?xml version='1.0' encoding='UTF-8'?><some xml>";
createHTTPRequestObject();
var resp = getResponseText(urlStr+"?"+xmlString,null);
var xmlDoc;
xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = false;
xmlDoc.loadXML(resp);
alert(xmlDoc.xml);
}
function createHTTPRequestObject(){
req=null ;
var pXmlreq = false ;
if (window.XMLHttpRequest) {
pXmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try{
pXmlreq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
try{
pXmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2) {
}
}
}
req = pXmlreq ;
}
function getResponseText(action,query,method,async,contenttype){
if(method==null){
method="POST";
}
if(async==null){
async="true";
}
if(contenttype==null){
contenttype = "application/x-www-form-urlencoded";
}
req.open(method,action, async);
req.setRequestHeader("Content-Type", contenttype);
if(query){
req.send(query);
}else{
req.send();
}
return req.responseText ;
}
</script>
</head>
<body>
<input type="button" name="Request" value="Request" onclick="sendRequest();"/>
<div id="content" />
</body>
</html>
You are trying to read the responseText before it is ready. Looks like you are treating a asynchronous call as synchronous. That would be the issue.
Related
Hi i am using this code for my AJAX JSON request but for some if i try to make jsonObj a global variable and console.log() it always comes up as undefined in the debugger console
To clarify my question, how can I retrieve a global variable from an AJAX JSON request
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class="src">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td>
<div id="Name">Sachin</div>
</td>
<td>
<div id="Country">India</div>
</td>
</tr>
</table>
<div class="central">
<button type="button" onclick="loadJSON()">Update Details </button>
</div>
The best way to approach this is by using what's called a callback function. A callback function is a function that is invoked when specific event takes place. In your case that event is the data being retrieved from your JSON endpoint (URL).
The proper way to do this is to create a function that will be called when your data is received and will then carry out the remaining logic. If you want to make that data also accessible globally, part of the callback function can update your global variable.
In the updated code below we first declare a global variable globalJSON that holds our data. Before you receive any data (i.e. before you click the button) the value of globalJSON.data will be null. Once the data is received the callback function updateView() is called with the received data. Inside of updateView() we update the global variable globalJSON.data and carry out the remaining logic (i.e. updating the required HTML elements).
You can then use globalJSON.data anywhere else in your code to get the data received when Update Details button was clicked.
// declare your global variable that will get updated once we receive data
var globalJSON = {
data: null
}
// this gets executed the moment you load the page - notice the value is null
console.log(globalJSON.data);
// this gets executed AFTER you receive data - notice call to updateView() inside AJAX call function
function updateView(data) {
// this will update the value of our global variable
globalJSON.data = data;
// this is the rest of the logic that you want executed with the received data
document.getElementById("Name").innerHTML = data.name;
document.getElementById("Country").innerHTML = data.country;
// this will show that the global variable was in fact updated
console.log(globalJSON.data);
}
function loadJSON() {
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try {
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
updateView(jsonObj);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
If you just want to access jsonObj from outside of the event handler, explicitly place it on the global scope (regardless of whether this is a good idea) you could create jsonObj on window by window.jsonObj = JSON.parse(http_request.responseText);
But you won't have any way of knowing when it's defined outside of the event handler. However, it would fulfill your requirement of being able to console.log(window.jsonObj) (presumably from the developer console). Also you could just console.log(jsonObj) in the eventhandler if you wanted to see the value.
full code:
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
function loadJSON(){
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
// if you want to be able to access this property from the developer console
window.jsonObj = JSON.parse(http_request.responseText);
// if you just want to see the value
console.log(JSON.parse(http_request.responseText));
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
</body>
Declare a variable at first like var jsonObj= ''; ( Inside your function. This variable is not global from the page context, but from the function context ). access the variable in your function. A problem in your url that you use http://www.tutorialspoint.com/json/data.json but the original site using https protocol. As a result you got an error something like that
Blocked loading mixed active content "http://www.tutorialspoint.com/json/data.json"
So change the url also to https://www.tutorialspoint.com/json/data.json.
Then you can parse the result as you want.
<title>tutorialspoint.com JSON</title>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON();">Update Details </button>
</div>
<script>
function loadJSON(){
var jsonObj= '';
var data_file = "https://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
// Javascript function JSON.parse to parse JSON data
jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
console.log(jsonObj);
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</body>
I watched Bucky's tutorial before and I cannot get this to work the error being shown is
index.php:62 Uncaught TypeError: Cannot read property 'documentElement' of undefinedhandleServerResponse # index.php:62
The JS is in the index.php here is the index.php
index.php
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if (window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(error)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(error)
{
xmlHttp = false;
}
}
if (!xmlHttp)
{
alert("XMLHttpRequest failed");
}
else
{
return xmlHttp;
}
}
function process()
{
if (xmlHttp.readyState === 0 || xmlHttp.readyState === 4)
{
var food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "ajax_content.php?food" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
}
else
{
setTimeout("process()", 1000);
}
}
function handleServerResponse()
{
if (xmlHttp.readyState === 4) //done loading
{
if (xmlHttp.status === 200)
{
var xmlResponse = xmlHttp.reponseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
document.getElementById("userInput").innerHTML = message;
setTimeout("process()", 1000);
}
else
{
alert("Error loading content");
}
}
}
</script>
</head>
<body onload="process()">
<input type="text" id="userInput" />
<div id="userInput">
</div>
</body>
</html>
And now ajax_content.php
ajax_content.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET["food"];
$foodArray = array("tuna", "bacon");
if (in_array($food, $foodArray))
{
echo 'We do have '.$food.'';
}
else if ($food == '')
{
echo 'Please enter a food'.$food.'';
}
else
{
echo 'We do not have '.$food.'';
}
echo '</response>';
?>
I read someones similar post but his was mainly syntax errors, why is this not working? What can I do to fix this?
believing this doc, and particularly this quote:
The XMLHttpRequest.responseXML property returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or if the response cannot be parsed as XML or HTML. The response is parsed as if it were a text/xml stream. When the responseType is set to "document" and the request has been made asynchronously, the response is parsed as a text/html stream.
and given you are receiving a 200 from the server, it probably means that your server didn't send you back valid xml.
You should inspect the response data using the network panel of you dev tools (press F12 in your browser).
I am trying to use XSL to translate an XML file into a neat table. For that I used the examples provided by W3schools which can be located here as a starting point. Yet the browser(chrome) is throwing the error that is described in the title of this post. I even tried copying the exact same example on W3 only to be met with the same error. Tried debugging in Firefox, this is the console output
TypeError: Argument 1 of XSLTProcessor.importStylesheet is not an object.
A similar question was posted before and the solution was in changing the model from synchronous to async. I tried doing that through the onreadystatechange method but without success. Here is the code I worked with.
<html>
<head>
<script>
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
return xhttp.responseXML;
}
};
xhttp.open("GET", filename);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
}
function displayResult()
{
xsl = loadXMLDoc("cdcatalog.xsl");
xml = loadXMLDoc("cdcatalog.xml");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
{
ex = xml.transformNode(xsl);
document.getElementById("dataTable").innerHTML = ex;
}
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("dataTable").appendChild(resultDocument);
}
}
</script>
</head>
<body onload="displayResult()">
<div id="dataTable" />
</body>
Thank you for all the help!
Here is an example of two asynchronous requests where the callback of one event handler starts the next request whose callback does the transformation. To keep it simple, I have used onload instead of onreadystatechange, if you really need support for old IE versions you will need to adapt the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XMLHttpRequest and onload handler with asynchronous requests</title>
<script>
function load(url, callback) {
var req = new XMLHttpRequest();
req.open('GET', url);
// to allow us doing XSLT in IE
try { req.responseType = "msxml-document" } catch (ex) {}
req.onload = function() {
callback(req.responseXML);
};
req.send();
}
function transform(xml, xsl) {
load(
xml,
function(inputXml) {
load(
xsl,
function(xsltSheet) {
displayResult(inputXml, xsltSheet);
}
);
}
);
}
function displayResult(xmlInput, xsltSheet) {
if (typeof XSLTProcessor !== 'undefined') {
var proc = new XSLTProcessor();
proc.importStylesheet(xsltSheet);
document.getElementById('example').appendChild(proc.transformToFragment(xmlInput, document));
}
else if (typeof xmlInput.transformNode !== 'undefined') {
document.getElementById("example").innerHTML = xmlInput.transformNode(xsltSheet);
}
}
</script>
</head>
<body onload="transform('catalog.xml', 'catalog.xsl')">
<div id="example"></div>
</body>
</html>
Online at http://home.arcor.de/martin.honnen/xslt/test2015072001.html, works fine with current versions of IE, Firefox and Chrome on Windows 8.1.
If you want to start two asynchronous requests directly to load XML and XSLT then you need to do some more work to make sure you know when both documents have been loaded to process them, an example of that is at http://home.arcor.de/martin.honnen/xslt/test2015072101.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XMLHttpRequest and onload handler with asynchronous requests</title>
<script>
function makeRequest(url, loadedData, property, elementToAddResult) {
var req = new XMLHttpRequest();
req.open('GET', url);
// to allow us doing XSLT in IE
try { req.responseType = "msxml-document" } catch (ex) {}
req.onload = function() {
loadedData[property] = req.responseXML;
if (checkLoaded(loadedData)) {
displayResult(loadedData.xmlInput, loadedData.xsltSheet, elementToAddResult);
};
};
req.send();
}
function checkLoaded(loadedData) {
return loadedData.xmlInput != null && loadedData.xsltSheet != null;
}
function loadAndTransform(xml, xsl, elementToAddResult) {
var loadedData = { xmlInput: null, xsltSheet: null };
makeRequest(xml, loadedData, 'xmlInput', elementToAddResult);
makeRequest(xsl, loadedData, 'xsltSheet', elementToAddResult);
}
function displayResult(xmlInput, xsltSheet, elementToAddResult) {
if (typeof XSLTProcessor !== 'undefined') {
var proc = new XSLTProcessor();
proc.importStylesheet(xsltSheet);
elementToAddResult.appendChild(proc.transformToFragment(xmlInput, document));
}
else if (typeof xmlInput.transformNode !== 'undefined') {
elementToAddResult.innerHTML = xmlInput.transformNode(xsltSheet);
}
}
</script>
</head>
<body onload="loadAndTransform('catalog.xml', 'catalog.xsl', document.getElementById('example'));">
<div id="example"></div>
</body>
</html>
I'm trying to test if the xml file have the tag "<group>"
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", "xmlfile.xml", false);
xmlhttp.send(null);
xml = xmlhttp.responseXML.documentElement;
var thegroup = xml.getElementsByTagName('group')[0];
if (!group) {
alert('No <group> in the XML: ' + xml);
return;
} else {
alert(xml + 'have a <group> tag');
}
Even if my xml file have the tag "<group>" the result is always negative, and the variable "thegroup" is undefined.
"xml" give me "[object Element]"
Where is my mistake?
PS: I'm only interested in webkit, I don't care about IE, Opera or Firefox for now.
EDIT : HERE IS MY ACTUAL CODE
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=UTF-8">
<title>xmltest</title>
<script type="text/javascript">
function init() {
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", "xmlfile.xml");
xmlhttp.send(null);
xmlhttp.onreadystatechange = callbackFunction;
function callbackFunction(){
if (xmlhttp.readyState == 4){
xml = xmlhttp.responseXML.documentElement;
var group = xml.getElementsByTagName('group')[0];
console.debug(xml)
if (!group) {
alert('No <group> in the XML: ' + xml);
return;
} else {
alert(xml + 'have a <group> tag');
}
}
}
};
</script>
</head>
<body onLoad="init();">
</body>
</html>
and my xmlfile.xml :
<?xml version="1.0" ?>
<group type="vertical">
<name>name</name>
<title>title</title>
</group>
At this point the alert is triggered saying :
No <group> in the XML: [object Element]
So maybe my problem is just on the way I try to find the <group> tag ?
XMLHttpRequest is asynchronous, it doesn't work that way. When you use xmlhttp.send(null); you have to define callback function that will be executed when the server responds with the data, otherwise you are trying to access empty data.
The code would look something like this:
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", "xmlfile.xml");
xmlhttp.send(null);
xmlhttp.onreadystatechange = callbackFunction;
function callbackFunction(){
if (xmlhttp.readyState == 4){
xml = xmlhttp.responseXML.documentElement;
var thegroup = xml.getElementsByTagName('group')[0];
if (!group) {
alert('No <group> in the XML: ' + xml);
return;
} else {
alert(xml + 'have a <group> tag');
}
}
}
this way, you are using onReadyStateChange to tell the browser to run callbackFunction everytime the server sends back a response. It tests for the readyState to be 4 which means that the request has been completely served.
var thegroup = xml.getElementsByTagName('group')[0];
if (!group) {
alert('No <group> in the XML: ' + xml);
return;
} else {
alert(xml + 'have a <group> tag');
}
What is group? Did you mean thegroup?
I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks
Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
Use:
new XMLHttpRequest
not
new xmlHttpRequest
I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>