How to call a PHP function with Ajax when the user clicks a button

  1. Create a child theme so you don’t mess with the code of an existing theme because next time you’ll update the theme, you may loose all your changes (see Child Themes)

  2. Here is how to pass values to your ajax request:

    jQuery(document).ready(function() { 
       jQuery(".mark-as-read").click(function () {
        console.log('The function is hooked up');
        jQuery.ajax({
            type: "POST",
            url: "/wp-admin/admin-ajax.php",
            data: {
                action: 'mark_message_as_read',
                // add your parameters here
                message_id: $('.your-selector').val()
            },
            success: function (output) {
               console.log(output);
            }
            });
        });
    });
    

You may do some research on Nonces too, to add a layer of security to your app: https://codex.wordpress.org/WordPress_Nonces

  1. Finally, the PHP code to handle the request (here too you should handle the nonce in real life code):

    // register the ajax action for authenticated users
    add_action('wp_ajax_mark_message_as_read', 'mark_message_as_read');
    
    // register the ajax action for unauthenticated users
    add_action('wp_ajax_nopriv_mark_message_as_read', 'mark_message_as_read');
    
    // handle the ajax request
    function mark_message_as_read() {
        $message_id = $_REQUEST['message_id'];
    
        // add your logic here...
    
        // in the end, returns success json data
        wp_send_json_success([/* some data here */]);
    
        // or, on error, return error json data
        wp_send_json_error([/* some data here */]);
    }
    

Leave a Comment