PHP - AJAX and MySQL

In this tutorial, we will see how to make Ajax work with PHP and MySQL. We will create a small web application. In that, as soon as you start typing an alphabet in the given input field, a request goes to the PHP file via Ajax, a query is made to the MySQL table, it returns some results and then those results are fetched by Ajax and displayed.

Example -

The PHP File

The page on the server called by the JavaScript above is a PHP file called "getuser.php". The source code in "getuser.php" runs a query against a MySQL database, and returns the result in an HTML table:

Example -

Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

  • PHP opens a connection to a MySQL server
  • The correct person is found
  • An HTML table is created, filled with data, and sent back to the "txtHint" placeholder