In this tutorial, I have created three files index.php, response.php and config.php. Front page (index.php) is the only file where user directly interacts with your application. response.php runs behind the scene, it has no visual contact with user and responds obliquely.
Let’s start by creating a MySQL table called add_delete_record. You can run SQL query below in your phpMyAdmin to create the table for you automatically.
Configuration file connects to specified database using MySQL credentials provided, the file is required in index.php and response.php. Edit config.php file to replace variables with your own MySQL username, pass and database name.
We’ll be using jQuery $.ajax method to make Ajax calls to response.php, if you examine jQuery code below, you can see that there are two click methods are used to make Ajax calls; .click() and .on().
The .click() and .on() method work same way, both get triggered when mouse button is pressed and released, the difference is that the .on() also attaches an event handler to the elements, for example: a button element loaded via Ajax request does not work with .click method, to make it work we must use .on() method to attach element to event handler. (For Older jQuery versions .live or .delegate() must be used instead). You can find additional documentation here.
Here’s how we list the initial records from the database using PHP.
As you can see we have some HTML input fields after the PHP code, which we will use to collect user input values which will be sent to the server. The loading image is set to “display:none“, it will remain hidden until user clicks submit button.
The response.php returns results according to the different Ajax request users make. response.php connects to database, add/delete records and return success / error messages. Since all these processing takes place on the server, we do not need any jQuery codes here.
In response.php, the type of request is determined by the POST variables sent by index.php. If content_txt POST variable is set, PHP code adds a new record and returns the result, if it is a delete request, it deletes selected record from the database.
In case of errors, we will just output PHP header 500 errors like this : header(‘HTTP/1.1 500 Error Message!’);. When we send this error message, Ajax response handler in index.php uses the HTTP status code to check if there was an error and alerts user with the message.