i

PHP Tutorial

AJAX Live Search

AJAX can also be used to create more user-friendly and interactive live searches on a webpage. Example, when you type something on Google, you get all the similar suggestions or the query you were going to type. So, instead of typing the whole sentence, you can easily click on the suggested inputs.

With AJAX live search, you will get the results as you type in the input field and will go on decreasing as you continue typing your sentence.

The search is started with the str.length function to check if the user is typing or not. Till user doesn’t type anything, no action is taken. But if the input field is not empty, then the function executes the below code.

  • An XMLHttpRequest object is created.

  • A function is created when the server response is ready.

  • The request is sent to the php file on the server.

The php code then searches for the matching words or sentences and returns the matching results. The XML file is loaded to a new XML DOM object, and a loop runs to find the matching results. The correct value is sent to the URL, and all matches are added to the variable and listed as suggestions. And, if no matches are found, then no suggestions is printed.

For AJAX live search, it is important to have quite long dataset so that user experience is more interactive and useful.