So I’m still learning around WordPress and can’t seem to figure out how to properly hook a nonce into a AJAX Form that I have created.
Here I am hooking and localizing the js file and defining a update_profile_validation
nonce [WORKS]:
function enqueue_scripts()
{
if (!is_admin()) {
wp_register_script('profile_edit_submit', content_url() . '/mu-plugins/fleishmanhillard/scripts/frontend-profile-edit.js', ['jquery'], '', true);
wp_localize_script( 'profile_edit_submit', 'profile_edit', [
// This will generate the admin URL that we can use on the front-end of our website
'ajax_url' => admin_url('admin-ajax.php'),
// Pass in a custom nonce name for JS
'nonce' => wp_create_nonce('update_profile_validation'),
]);
wp_enqueue_script('profile_edit_submit');
}
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');
This method is used to update the user content [WORKS]:
function ajax_update_profile_post($args)
{
check_ajax_referer('update_profile_validation', 'my_nonce');
update_profile_post($args);
wp_die();
}
add_action( 'wp_ajax_update_profile_post', 'ajax_update_profile_post' );
function update_profile_post($args = [])
{
if (!$args) {
return;
}
// If the server request is POST, proceed to update post
if (strtolower($_SERVER['REQUEST_METHOD']) === "post") {
wp_update_post($args);
}
}
Here is my AJAX form submission [WORKS]:
(function ($) {
$(function($) {
$('#profile_update').on('submit', function(e) {
$.ajax({
type: 'POST',
url : profile_edit.ajaxurl,
data: $('#profile_update').serialize() +
'&my_nonce=" + profile_edit.nonce +
"&action=update_profile_post'
});
return false;
});
});
})(jQuery);
Here is the final part of my form:
<?php if ($profile->get_edit_post_link()):
// Set the post field content field
$post_content = $_POST['content'];
ajax_update_profile_post([
'ID' => $profile->get_id(),
'post_content' => $post_content,
]);
?>
<form action="" id="profile_update" method="POST">
<input type="text" name="content" id="post_content">
<button type="submit"><?= 'Update Post' ?></button>
<?php wp_nonce_field('update_profile_validation', 'my_nonce'); ?>
</form>
<?php endif;
So the form works and the field submits and all, but I’m having a difficult time understanding how to apply a proper nonce to the form.. All assistance would be appreciated!