Help with AJAX request

The code you provided is on the right track, but it’s possible that the issue you’re facing is related to WordPress’s admin-ajax.php handling.

Here’s how you can modify your code to make sure you stay on the same page after submitting the form:

  1. Change the form action to the current page instead of admin-ajax.php.

Form:

<form action="<?php echo esc_url(admin_url('admin-ajax.php')); ?>" method="POST" id="comment_form">
  1. Modify your JavaScript
<script>
jQuery(function($) {
    $('#comment_form').submit(function(e) {
        e.preventDefault(); // Prevent the default form submission

        var commentform = $(this);
        $.ajax({
            url: commentform.attr('action'),
            data: commentform.serialize(), // Form data
            type: commentform.attr('method'), // POST
            beforeSend: function(xhr) {
                commentform.find('button').text('Processing...');
            },
            success: function(data) {
                commentform.find('button').text('Add Comment');
                $('#response').html(data); // Insert data
            }
        });
    });
});
</script>
  1. Make sure your JavaScript code is enqueued properly in your WordPress theme or plugin.

  2. Ensure that the JavaScript code is loaded on the page where the form is present.

With these changes, your form should be submitted via AJAX, and the page will not be redirected to admin-ajax.php. Instead, the response will be loaded into the #response div on the same page.

tech