views:

77

answers:

2

Hello.

I have a text field. When I type something into than text field, I want to load stuff into the DIV below. That's my code equivalent:

<input type="text" onkeyup="/* I am not sure how it's done, but I'll just write: */ document.getElementById('search_results').innerHTML = getContents('search.php?query='+this.value);" /><br/>
<div id="search_results"></div>

Hope you can help. Thanks in advance!

EDIT: I would appreciate it if the solution did not involve using jQuery - as long as it's possible.

ANSWER: How I'm doing it:

<input type="text" onkeyup="loadSearchResults(this.value)" /><br/>
<div id="search_results"></div>

<script>
function loadSearchResults(query){

if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
    var xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
    var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("search_results").innerHTML=xmlhttp.responseText;
    }else if(xmlhttp.readyState>=1 && xmlhttp.status==200){
        // show the ajax loader or stuff like that...
    }
}
xmlhttp.open("GET","search.php?search="+query,true);
xmlhttp.send();

}
</script>
+2  A: 
acrosman
OK. Now, if I install jQuery, how would I do this then?
arik-so
You read up on jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Gert G
I added a few more details to extend the answer, details vary widely depending on setup, but this should get you pointed in a productive direction.
acrosman
This seems great! Thanks! I will try it out. Still, I'm very interested to know how I can use this jQuery ajax command with JavaScript. It's something about XMLHTTPRequest or sth. like that, I'm extremely unexperienced with AJAX, but I really need to know. Thanks in advance!
arik-so
jQuery handles the cross-browser issues related to doing XMLHTTPRequests for you. It's probably worth the effort to find a tutorial that describes to do the requests directly (like http://w3schools.com/ajax/ajax_intro.asp), but I'd stick to popular libraries of for actual production use.
acrosman
In the meantime, I have visited W3Schools to, and I have managed!
arik-so
A: 

You would do something like:

$("#inputid").keyup(function(evt) {
    $("#search_results").load("/getresults.php", {queryparam: evt.target.value});
});

Of course, it does end up being more complicated than that. You probably don't want to send a request to the server on every key press.What happens if the server takes a long time to respond? Should you provide some indication that a request to the server is being made?

If you use jQueryUI, you can use the autocomplete widget, which might get you closer to then end result you want.

lambacck