简体   繁体   中英

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);
  }
}

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);

It's not working on IE, rest of the responses and suggestions here are correct. Why IE only? because you have undefined vars:

searchString = searchBox.value;

correct

var searchString = searchBox.value;

To check if your script is truly working just alert the formatted string.

article.innerHTML += string;
alert(string);

then you will know what is wrong.

If you're using a button in a form to post with AJAX, make sure the button type="button" or it will act as a submit button and submit the form. This little feature cost me days of frustration!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM