Ajax has made the web loading faster and more powerful. Prior to Ajax, the pages were loaded over and over for small changes within thus making the web experience slower. The load on the web server is also minimized as only the required content is sent to the client browser instead of re-sending the same unwanted HTML, CSS. Using Ajax, the webpage is updated for the required values.
This tutorial can be helpful in knowing the power of Ajax where a webpage is updated with the values from MySQL database. I have created a table of List of Presidents of the United States after 1975. The President’s name can be selected from a drop-down select box and the part of the webpage will be updated with the retrieved information from database.
The tutorial can be carried by following steps –
- Create Database table for storing the List of Presidents
- Create HTML page to show the details of the Presidents
- Create a logic page using PHP to retrieve values from database
1. Create Database table for storing the List of Presidents
Following query will create the required table to store the information.
The table structure should look something like this –
2. Create HTML page to show the details of the Presidents
This is basically the View component. The drop-down select list and the retrieved content is shown on this page.
First, we’ll create the drop down list so that users can select the ‘President’ to see the corresponding details.
Now, let us add the AJAX code on this page. The code is added in the head section of the page in the <script> tags.
Once the option is selected using ‘onChange’ event, getPresident function is called with the selected option value.
The page should look like this,
3. Create a logic page using PHP to retrieve values from database
This page takes the ‘id’ from the html page we created, retrieves details of the President and finally generates HTML response which is fetched asynchronously on the html page.