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!!