During the course of web development, you will certainly come across a use case to send data from Javascript to PHP and back. The reason being that, Javascript is used on client side and PHP is used on the server side. We had a user requirement once, that demanded such a scenario. The requirement itself was easy to understand, but a little tricky to implement.
Consider a use case where a row can be deleted from a table, if user clicks delete.
- A table has to be displayed, with a delete option for every row.
-
The delete option is provided as a link.
-
Every time the delete link is clicked, the corresponding row has to be deleted.
To implement this, we would have to use jQuery and PHP. How and Why is explained below.
Creating the table and Providing a delete link
The table is created using a form. Data for each row of the table, is fetched from the WordPress database. Each row is displayed using a simple for loop, inside the form. The delete link, is added in every row as follows:
<a href='' name='delete' row_id='$id' class='delete_row' style='color:red'>Delete</a>
where row_id is set to the id of the corresponding row, fetched from the database. This is to associate the delete link with the row.
Each delete link, has the same name ‘delete’. Thus if we get the row_id directly from the $_POST variable, always the row_id of the last instance will be sent and not necessarily the one the user has clicked.
To know which link the user has clicked, we have to handle the clicked event, using jQuery. And store the value of row_id, of the clicked link, in a hidden variable in the form itself. The value of this hidden variable can then be retrieved from the $_POST variable and the appropriate row can be deleted.
Providing a hidden variable to store the row_id
This hidden variable will be part of the form, but outside the table, as a separate element.
<input type='hidden' name='del_id' id='row_del_id' value=''>
Handle Delete link Clicked
On delete link clicked, jQuery will fetch the id of the row, row_id, to be deleted.
<script> jQuery('.btn_delete_row').click(function() { var current_id = jQuery(this).attr('row_id'); // assign the row_id to the hidden field jQuery('#del_id').val(current_id); // submit the form, to retrieve the del_id value from $_POST jQuery( "#form1" ).submit(); return false; }); </script>
Perform Delete Operation
When the form is submitted, we can retrieve the value of the hidden field and delete the row.
if(isset($_POST['del_id'])) { $delete_row_id=$_POST['del_id']; global $wpdb; $example_table=$wpdb->prefix.'table_prefix'; $wpdb->delete($example_table, array('example_row_id' => $delete_row_id), array('%d')); }
Using this simple idea, of providing a hidden field in the form, we could solve our problem of sending data from jQuery to PHP. If you had any questions regarding this, you could let us know through the comment section below.
Further Reading: