Adam Piper Adam Piper - 1 year ago 54
Ajax Question

AJAX works when in debug mode but not in real time

My code works when i'm slowly stepping through in debug mode, but when i try it in real time, it doesn't seem to want to update the page.
Here is the javascript:

searchButton = document.getElementById("searchButton");
var searchBox = document.getElementById('searchBox');

searchButton.addEventListener("click", searchItem);

function searchItem(){
searchString = searchBox.value;
article = document.getElementById("homeSection");
var xmlhttp = getXmlHttpRequestObject();
var string = '';
if(xmlhttp){
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var response = JSON.parse(xmlhttp.responseText);
for(var i=0; i<response.length; i++){
string += '<section class="searchResult">';
string += '<h1>' + response[i].Name + '</h1>';
string += '<p class="photo"></p>';
string += '<p class="price">£' + response[i].Price + '</p>';
string += '<p class="productID">ID: ' + response[i].ID + '</p>';
string += '<p class="description">' + response[i].Description + '</p>';
string += '<p class="quantity">Quantity: ' + response[i].Quantity + '</p>';
string += '</section>';
}
article.innerHTML = '<h1>Search</h1><section><h1 class="bottomBorder">You searched for: "' + searchString + '"</h1></section>';
article.innerHTML += string;
}
};
xmlhttp.open("GET", "search.php?search=" + searchString, true);
xmlhttp.send(null);
}
}

Answer Source

Two things you need to do

  1. Cancel the click action that is triggering the function
  2. Second encode the content you are sending to the server

Updated code:

function searchItem (event){
    event.preventDefault();
    var searchStringEnc = encodeURIComponent(searchBox.value);
    ...
    xmlhttp.open("GET", "search.php?search=" + searchStringEnc, true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download