Managing Ajax comment submit

We will now expand our Ajax knowledge with Ajax submit form technique.

The principle remains the same. jQuery will respond to an event (in this case, a user submitting the form) and instead of reloading the page, it will call an external script and display the results.

Our script on the other end will receive form information, and after validation, insert the comment into the WordPress database.

Finally, we will show a status message to the user, letting them know that the comment has been accepted:

Managing Ajax comment submituser inputhandling

In this example, we will learn how to handle submit forms using Ajax.

We will also learn how to save the comments in the WordPress database.

  1. Create the wp-wall-ajax.php file which will handle submitted form through a series of simple checks:
    <?php
    require_once("../../../wp-config.php");
    if ($_POST['submit_wall_post'])
    {
    $options = get_option('wp_wall');
    $comment_post_ID=$options['pageId'];
    $actual_post=get_post($comment_post_ID);
    // sanity check to see if our page exists
    if (!$comment_post_ID || !$actual_post || ($comment_post_ID!=$actual_post->ID) )
    {
    wp_die('Sorry, there was a problem posting your comment. Please try again.');
    }
    // extract data we need
    $comment_author = trim(strip_tags($_POST['author']));
    $comment_content = trim($_POST['comment']);
    // If the user is logged in get his name
    $user = wp_get_current_user();
    if ( $user->ID )
    $comment_author = $user->display_name;
    // check if the fields are filled
    if ( '' == $comment_author )
    wp_die('Error: please type a name.');
    if ( '' == $comment_content )
    wp_die('Error: please type a comment.');
    // insert the comment
    $commentdata = compact('comment_post_ID', 'comment_author', 'comment_content', 'user_ID');
    $comment_id = wp_new_comment( $commentdata );
    // check if the comment is approved
    $comment = get_comment($comment_id);
    if ($comment->comment_approved==0)
    wp_die('Your comment is awaiting moderation.');
    // return status
    die ( 'OK' );
    }
    Ajax formsubmit form, handling?>
    
  2. Now, create the wp-wall.js file to handle our jQuery and Ajax stuff:
    // setup everything when document is ready
    jQuery(document).ready(function($) {
    $('#wallform').ajaxForm({
    // handler function for success event
    success: function(responseText, statusText) {
    $('#wallresponse').html('<span class="wall-success"> '+'Thank you for your comment!'+'</span>');
    },
    // handler function for errors
    error: function(request) {
    // parse it for WordPress error
    if (request.responseText.search(/<title>WordPress &rsaquo; Error<\/title>/) != -1) {
    var data = request.responseText.match(/<p>(.*)<\/p>/);
    $('#wallresponse').html('<span class="wall-error">'+ data[1] +'</span>');
    } else {
    $('#wallresponse').html('<span class="wall-error">An error occurred, please notify the administrator.</span>'); }
    } ,
    beforeSubmit: function(formData, jqForm, options) {
    // clear response div
    $('#wallresponse').empty();
    }
    });
    });
    
  3. We now need to load our script, jQuery and jQuery-Form libraries. The latter is used for handling Ajax form submits.
    add_action('wp_print_scripts', 'WPWall_ScriptsAction');
    function WPWall_ScriptsAction()
    {
    global $wp_wall_plugin_url;
    wp_enqueue_script('jquery');
    wp_enqueue_script('jquery-form');
    Ajax formsubmit form, handlingwp_enqueue_script('wp_wall_script',$wp_wall_plugin_url. '/wp-wall.js', array('jquery', 'jquery-form')); }
    
  4. Add the URL to our Ajax handler script to the form's action field in wp-wall-widget.php. This is the script that will be called when the user clicks on Submit.
    <div id="wall_post">
    <form action="<?php echo $wp_wall_plugin_url.'/ wp-wall-ajax.php'; ?>" method="post" id="wallform">
    
    <?php if ( $user_ID ) : ?>
    
  5. Add a<div> for script responses at the end of the form. We will use it to show status messages:
    <p><input name="submit_wall_post" type="submit" id="submit_wall_post" tabindex="3" value="Submit" /></p>
    </form>
    </div>
    <div id="wallresponse"></div>
    
    </div>
    
  6. Update all the files. You are now ready to post comments:
    Time for action — Save the comments
  7. And if you go to the Manage Comments administration panel you can see our comments listed:
Time for action — Save the comments

Congratulations! An important part of the plugin functionality has been achieved.

We can now add as many comments as we want and manage them through our WordPress administration panel.

The jQuery form module provides the ajaxForm() method, which can automatically handle form submits using Ajax. It hooks to necessary events (like the user pressing the Submit button), submits the form dynamically using an Ajax call and displays the results.

We use the ajaxForm method with #wallform, which is the ID of our form:

The ajaxForm() function provides three useful events we can use for extra configuration.

The first is beforeSubmit, which executes just before the form is submitted. It is usually used to process the fields or do some kind of form validation.

In our case, we will clear the response<div>.

Next, we will hook up to the error event, which executes in the event of a script failure.

Since we are using wp_die() to exit our comment handling script, we need to parse the response:

If the response is valid, we extract the error message and print it out in our wallresponse div:

Since we are using WordPress comment handling, we can expect errors ranging from duplicate comments, comment flooding, protection, and so on. We get all this comment checking functionality for free.

Using Ajax to submit forms

In case of wrong or malformed error response, we will print out a default error message:

Finally, we will hook up to the success event, which will run when our comment is submitted successfully. If everything goes fine, we will print out a simple 'Thank you' message:

Let's see how the submitted comments are parsed and saved by WordPress.

We check the $_POST variable first to confirm that a comment is being posted:

Next, a sanity check is performed to see if everything is all right with our wall page that is used for saving the comments:

We use wp_die() to exit from our script in case of an error, passing it the error message. This will also automatically cause the Ajax call to return an error status.

Next, we extract the comment fields from the $_POST variable:

If the user is logged in, we want to use his display name as the comment author's name.

To do this, we use wp_get_current_user(). It returns an object containing user information such as user ID and name.

Now, we can proceed to insert the comment. First, we use compact() to fill the comment data into an array, passing it the variables we need. We insert the comment using the wp_new_comment function.

After the comment is inserted, we check to see if it was approved or not. Some blog administrators like to keep all the comments for approval, in which case the comment will not show up immediately:

Finally, if everything is ok, we use die() method to just exit the script. The parameter is optional in this case, as we are not showing it anywhere:

Note

Quick reference

ajaxForm(options) (jQuery): Used to submit forms with Ajax. The options object has among others are the success, error and the beforeSubmit callback events. More information can be found at:http://www.malsup.com/jquery/form/

wp_get_current_user(): Returns information about the current user in an object including ID, display_name, email, and so on. More information can be found at:http://codex.wordpress.org/Function_Reference/get_currentuserinfo

wp_new_comment($commentdata): Inserts a comment into the database accepting the comment data array; returns a comment ID.

get_comment($id): Takes a comment ID and returns comment information in an object. We used it to check the comment_approved field. More information can be found at:http://codex.wordpress.org/Function_Reference/get_comment

wp_die($message): Exits the script returning Internal server error 500 HTTP header and the specified error message.