6

I'm developing a wordpress site using custom templates/themes, but I'm having trouble. I want to use Ajax to call a function when a user clicks a button. On one page, I have a button like so:

<p class='form-submit'>
        <input name='message_read' type='submit' class='submit button mark-as-read' value= 'Mark as read' />
    </p>

And I have a jQuery/Ajax function like this:

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',
        },
        success: function (output) {
           console.log(output);
        }
        });
    });
});

The function above lives in wp-content/themes/my-theme/js/wp_ajax_calls.js. I added the script to the site like so:

1) I added this to my functions.php file:

wp_enqueue_script(  'ajax calls', get_template_directory_uri() .'/js/wp_ajax_calls.js', array('jquery'), '1.0', true);

2) I included the script in the header.

<script type="text/javascript" src="https://mysite//wp-content/themes/twentyfifteen/js/wp_ajax_calls.js"></script>

When I click the button as is, the console.log statement shows up. To my understanding, I want my ajax function to call a php function that will let me use $wpdb. I have this in functions.php:

function mark_message_as_read() {
    global $wpdb;
    // do stuff. 
}

This is where I am getting confused. I have two main questions:

1) I think I am supposed to have some add_action() 's somewhere, but I don't know where to put them and I also don't know what hook I should use.

2) Additionally, I want to be able to pass data (the message id) to the php function for my db query. How do I pass an argument to that function?

I don't want to use something like if( isset($_POST['message_whatever']) ) twentyfifteen_message_whatever(); because of the way I have messages set up.

Happy to provide more information if needed. Thanks in advance for your help!!

1

1 Answer 1

12
  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 */]);
    }
    
1
  • Thank you very much! I'll definitely take a look at nonces as well. :D
    – ellen
    Commented Sep 8, 2018 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.