A client wanted me to use Ajax to save checkbox results to a database so that each check was saved as it was made instead of waiting until all the checkboxes were checked (or unchecked) and then submitted on the form. He had a LOT of checkboxes on the page which made a very large form with lots of fields. The chance the user might leave the page before the submit button was hit was just too big of a risk. He wanted each check to be saved.
We used jQuery and Ajax to make it happen:
// <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> <script> function save_checkbox(checkbox_id, record_id) { $.post( 'test.php' , { checked : checkbox_id, r_id : record_id }, function( response ) { //alert(response); $( "#result" ).html( response ); } ); } </script> <div id="result"></div> <!-- div to hold results from ajax --> <input name="val" type="checkbox" value="<?php echo $val ?>" onclick="save_checkbox('to_print',<?php echo $id ?>);"; //
This jQuery/javascript function will be called each time a checkbox is clicked whether it’s checked or unchecked. The post jQuery method will call the test.php
file and pass checked
and r_id
as post variables. The value of checked
will be what’s passed from the input tag in checkbox_id and the value of r_id
will be the value passed into the record_id
variable by the input tag.
In other words, the input tag will create the following checkbox.
checkbox to toggle
When it’s clicked, it will pop up a javascript alert box and then replace the following with the results from the file.
The checkbox is using onclick="save_checkbox('to_print','13')"
so that 'to_print'
is passed to checked_id
and '13'
is passed to record_id
in the save_checkbox function. These variables are passed in the $_POST
to the php script called by the jquery .post method. The php file ‘test-ajax.php’ is called from the .post method. That file contains this code:
// <?php // whatever you echo or print will be passed back into the 'response' variable in the call back function echo '<strong>results from the script - passed in: '; // these are the variables passed in print_r($_POST); print('</strong>'); // Your code here - take out the previous two statements when you are ready, the output any response you want to send back with echo or print. ?> //
You can execute this file by clicking this link to see the output: https://cullenwebservices.com/test-ajax.php
Wow. This is *exactly* what I was looking for, and such a clear explanation too. Thank you very much, this has been of enormous help. (Purely for interest, I’m updating standard, synchronous POST code to store additional user meta information in a WordPress database. In particular, whether a person’s name uses Japanese/Chinese/Korean characters for which I need to use a different font when generating downloadable PDF documents. But expanding to store more options and I face the exact issue as is described and solved here – so thanks again! ).