So I’m having some issues with my AJAX form submission and I can’t seem to figure out why, below I will be explaining all the steps that I will be taking to attempt to submit the form.
The scripts are enqueued [WORKS]: Ensures that the file holding the ajax request is loaded which it is.
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 updates the post ID’s post_content [WORKS]: On submission, it updates the database content of the right ID.
if (strtolower($_SERVER['REQUEST_METHOD']) === "post") {
// @todo: Make sure that the account is associated with the logged in account on profile edits
// If profile isn't empty, continue
if (!empty($profile)) {
// Grab the content submitted
// @todo: Figure out how to set the $_POST request to a function
$post_content = $_POST['content'];
wp_update_post([
'ID' => $profile->get_id(),
'post_content' => $post_content,
]);
}
}
HTML [WORKS]:
<form action="" id="profile_update" method="POST">
<input type="text" name="content" id="post_content" class="required">
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit"><?= 'Update Post' ?></button>
</form>
PROBLEM: So the submission works but it refreshes the page on submit, but I’d like to move forward with an AJAX submission but I don’t know where to begin.. here is what I have, but it’s not working correctly.
(function ($) {
$(function($) {
$('.profile_update').on('click', function() {
$.ajax({
type: 'POST',
url: profile_edit.ajaxurl,
data: {
}
});
});
});
})(jQuery);
When I submit the form, it updates the database and also changes the server request from GET to POST.
2
Answers
change the html this way
you are selecting a CSS class by using
.
in jQuery you need to use#
it should be
we have to change the javascript.