Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AJAX Script slow

Status
Not open for further replies.

NetworkGhost

IS-IT--Management
Apr 12, 2005
1,324
US
Got a quick question. Got some slowness in my javascript that I dont experince when I go to the page itself. Hopefully someone can point me in the right direction:

Here is the script:

Code:
var xmlHttp

function showResult(str)
{
if (str.length==0)
 {
 document.getElementById("livesearch").
 innerHTML="";
 document.getElementById("livesearch").
 style.border="0px";
 return
 }

 xmlHttp=new XMLHttpRequest();
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }

var url="livesearch.php"
url=url+"?q="+str
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 {
 document.getElementById("livesearch").
 innerHTML=xmlHttp.responseText;
document.getElementById("loading").
 innerHTML="";
 }
else {
 document.getElementById("loading").
 innerHTML="<img src='121339176329.gif' height='400' width='400' >";
}
}

When I render the URL the script is calling it loads quite quickly. When I use the javascript AJAX method it takes a few seconds. Was wondering if there is something Im missing or a better way to accomplish.

 
You could try creating one reference to each element on the page; this may speed things up a bit for you.

Something like this;
Code:
var xmlHttp = new XMLHttpRequest() ;
var livesearch = document.getElementById("livesearch") ;
var loading = document.getElementById("loading") ;

function showResult(str)  {
  
  if (str.length==0) {
    livesearch.innerHTML="";
    livesearch.style.border="0";
    return ;
  }

  if (xmlHttp==null) {
    alert ("Browser does not support HTTP Request") ;
    return ;
  }

  var url="livesearch.php?q="+str ;
  xmlHttp.onreadystatechange=stateChanged;
  xmlHttp.open("GET",url,true) ;
  xmlHttp.send(null) ;
}

function stateChanged() {
  if (xmlHttp.readyState==4) {
    livesearch.innerHTML=xmlHttp.responseText;
    loading.innerHTML="";
  } else {
    if (xmlHttp.readyState == 1) {
      // initialized ... show loading image once
      loading.innerHTML="<img src='121339176329.gif' width='400' />";
    }
  }
}





Greg
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top