Reputation: 555
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);
}
}
Upvotes: 0
Views: 875
Reputation: 1
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!!!
Upvotes: 0
Reputation: 4902
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.
Upvotes: 0
Reputation: 207501
Two things you need to do
Updated code:
function searchItem (event){
event.preventDefault();
var searchStringEnc = encodeURIComponent(searchBox.value);
...
xmlhttp.open("GET", "search.php?search=" + searchStringEnc, true);
Upvotes: 1