The answer is YES... you can get real-time response when a user types something, however some are the points to take into account.
In the case of using JQUERY and PHP as requested, request by AJAX is the path to take.
In an analysis simplistic you will need to "listen" to keystrokes in INPUT.
example with keypress but there is the keyup or the keydown (enter, for other keys see documentation):
$( "#target" ).keypress(function( event ) {
if ( event.which == 13 ) {
alert('enter pressionado');
}
});
As a result of each key pressed you can obtain the contents of INPUT:
var content = $( "#target" ).val();
Hand over content
at the asynchronous HTTP (Ajax) request
and so it is returned by webservice
search result update the html
.
As I said this is a simplistic way and why?
Because the speed of delivery of the search result will never be the same and because who type fast... imagine the requests
successive. Good indeed with the implementation of a requests QUEUE can overcome this problem, but again it would not be practical in this particular case.
It is not good practice to perform AJAX requests
at the speed the text is entered. And if the webservice is well prepared it will definitely block a certain point or refuse to respond. Don’t forget that a webservice is an exposed service, soon accessed by many. Imagine everyone typing at the same time. :)
If the webservice
is "yours" then you will determine the rules, however, unfortunate of the server that answer for a service exposed in this way.
There are some techniques to implement but I leave a simple that will have immediate results, ie the use of a timer... example: setTimeout. imagine something like:
$.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, I did not test it but the logic will certainly not be very different. Each key pressed will be validated when it is "dropped" and the timer restarts.
For simplicity the character must be greater than 45 (see table). When you stop typing then the timer will wait for the stipulated time. In the example is 200 milliseconds and executes the code inside the setTimeout()
.
Perform tests and adjust the value of the timer. Increase its value, however, the longer the search takes.
I put validations that reminded me that the timer should be restarted when typing, as space key (32), Backspace (8) and enter (13)... see other hypotheses because it is an example.