skip to Main Content

I am creating an events plugin with a commenting section for each event. I am able to save each comment, but the problem I’m having now is that I am taken to admin-ajax.php which is blank. When the form is submitted, I want to stay on the same page and have results loaded. I understand that by having the form action set to admin-ajax.php, it is going to end up on that page, but I have tried different ways I have found by searching with Google and this is the only way I have been able to get it to save to the database. My code is below.

Form

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="comment_form">
    <textarea name="comment" id="comment" class="commentbox" rows="5" cols="120" required></textarea><br />
    <input type="hidden" name="eventid" id="eventid" value="<?php echo $id; ?>" />
    <input type="hidden" name="userid" id="userid" value="<?php echo $userid; ?>" />
    <input type="hidden" name="action" value="commentform">
    <button class="commentbtn">Add Comment</button>
</form>
<div id="response"></div> 

jQuery

<script>
jQuery(function($){
    $('#commentform').submit(function(){
        var commentform = $('#commentform');
        $.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
            }
        });
        return false;
    });
});
</script>

PHP Function

add_action('wp_ajax_commentform', 'comment_submit'); 
add_action('wp_ajax_nopriv_commentform', 'comment_submit'); 
function comment_submit() { 
    global $wpdb; 
    $eventid = $_POST["eventid"];
    $userid = $_POST["userid"]; 
    $comment = $_POST["comment"];
    date_default_timezone_set("America/New_York");
    $date = date('Y-m-d H:i:s');

    $inserttable = $wpdb->prefix . "event_comments";
    $data = array(
        'eventid' => $eventid,
        'userid' => $userid,
        'content' => $comment,
        'datesaved' => $date,
    );
    $wpdb->insert($inserttable, $data);

    die;
}

2

Answers


  1. Chosen as BEST ANSWER

    I figured it out. I forgot to add event.preventDefault(); to stop the form from loading.


  2. Sorry i can’t comment.

    Reading your code, the element your are looking for does not exist :
    Replace comment_form by commentform.

    $('#commentform').submit(function(){
        var commentform = $('#commentform');
    

    But your id attribute is id="**comment_form">

    <form  ...  id="comment_form">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search