Ajax Add & Delete MySQL records using jQuery & PHP
In this tutorial, we have mainly three PHP files index.php, response.php and config.php (For saving MySql credentials). Front page (index.php) populates initial records from the database and also contains a text input field, which users can use to send Ajax data to response.php.
Users have no visual contact with response.php, this file just sits behind the scene; waiting for any POST data. The main task of response.php is to return data or errors back to the front page.
Let’s start by creating a MySQL table called add_delete_record. You can run SQL query below in your phpMyAdmin, it should automatically create the table for you.
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 HTML and PHP code :
Returning the Data
The response.php returns results according to the different Ajax request users make. response.php can connect 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.
Another notable thing I want to highlight here is error output method, we can return a custom 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.
Saran Chamling. (He loves the web technology, and enjoys designing, exploring and writing about it @saaraan.com).