The answer is YES ... you can get a real-time response when a user types something, however there are some points to keep in mind.
In case of using JQUERY and PHP as requested, AJAX request is the way to go.
On a simplistic parsing you will need to "hear" key events in INPUT.
example with keypress but there is either the keyup or the keydown (I enter enter, for other keys see documentation):
$( "#target" ).keypress(function( event ) {
if ( event.which == 13 ) {
alert('enter pressionado');
}
});
As a result of each key press you can get the INPUT contents:
var content = $( "#target" ).val();
Deliver content
to asynchronous HTTP (Ajax) request
and as soon as it is returned by webservice
search result update html
.
How did you say this is a simplistic way and why?
Because the delivery speed of the search result will never be the same, and because fast typing ... imagine the requests
successive. Well actually with the implementation of a QUEUE of requests can overcome this problem, but again would be nothing practical in this particular case.
It is not good practice to AJAX requests
at the speed that text is entered. And if the webservice is well prepared you will certainly block at a certain point or refuse to respond. Do not forget that a webservice is an exposed service, soon accessed by many. Imagine everyone typing at the same time. :)
If the webservice
is "your" then you will determine the rules, however, unfortunate server that respond for a service exposed in this way.
There are some techniques to implement but I leave a simple one that will have immediate results, ie the use of a timer ... example: setTimeout. imagine something of the sort:
$.fn.input_search = function () {
var timer = 0;
var input = $(this);
input.keyup(function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code > 45 || code === 32 || code === 8 || code === 13) {
clearTimeout(timer);
timer = setTimeout(function () {
alert('neste momento coloca a chamada AJAX '.input.val())
}, 200);
}
});
};
I created this plugin, did not test it but the logic will certainly not be very different. Each key pressed will be validated when it is "started" and the timer is reset.
For simplicity, the character must be greater than 45 (see table). When you stop typing, the timer will wait for the stipulated time. In the example it is 200 milliseconds and runs the code inside setTimeout()
.
Perform tests and adjust the timer value. Increase your value, however, the longer it takes, the longer the search starts.
I put validations that reminded me that the timer should be restarted by typing, like space key (32), backspace (8) and enter (13) ... see other hypotheses because it is an example .