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:
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.
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?>
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 › 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(); } }); });
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')); }
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 ) : ?>
<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>
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.
When the user submits a form, normally the URL given in the form's action is called:
<form action="<?php echo $wp_wall_plugin_url. '/wp-wall-ajax.php'; ?>" method="post" id="wallform">
If we do not use jQuery Ajax to handle submissions, our browser will load wp-wall-ajax.php
as a new page and show the output of the script.
However, jQuery form library allows us to assign form submissions to Ajax calls easily.
So we have loaded all the necessary libraries using the wp_print_scripts
action hook:
add_action('wp_print_scripts', 'WPWall_ScriptsAction'); function WPWall_ScriptsAction() { global $wp_wall_plugin_url; wp_enqueue_script('jquery'); wp_enqueue_script('jquery-form'); wp_enqueue_script('wp_wall_script', $wp_wall_plugin_url.'/ wp-wall.js', array('jquery', 'jquery-form')); }
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:
// setup everything when document is ready jQuery(document).ready(function($) { $('#wallform').ajaxForm ({
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>
.
$('#wallform').ajaxForm ({
beforeSubmit: function(formData, jqForm, options)
{
// clear response div
$('#wallresponse').empty();
}
});
});
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:
// setup everything when document is ready
jQuery(document).ready(function($)
{
$('#wallform').ajaxForm ({
// handler function for errors
error: function(request) {
// parse it for WordPress error
if (request.responseText.search(/<title>WordPress › Error<\/title>/) != -1) {
If the response is valid, we extract the error message and print it out in our wallresponse
div:
// parse it for WordPress error
if (request.responseText.search(/<title>WordPress › Error<\/title>/) != -1) {
var data = request.responseText.match(/<p>(.*)<\/p>/);
$('#wallresponse').html('<span class="wall-error">'+ data[1] +'</span>');
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.
In case of wrong or malformed error response, we will print out a default error message:
} 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();
}
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:
// setup everything when document is ready
jQuery(document).ready(function($) {
$('#wallform').ajaxForm({
// handler function for success event
Ajax formused, to submit formssuccess: function(responseText, statusText) {
$('#wallresponse').html('<span class="wall-success">'+'Thank you for your comment!'+'</span>');
},
// handler function for errors
error: function(request) {
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:
if ($_POST['submit_wall_post']) {
Next, a sanity check is performed to see if everything is all right with our wall page that is used for saving the comments:
$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.');
}
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:
// extract data we need $comment_author = trim(strip_tags($_POST['author'])); $comment_content = trim($_POST['comment']);
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.
// If the user is logged in get his name Ajax formcomments, saving$user = wp_get_current_user(); if ( $user->ID ) $comment_author = $user->display_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.
// insert the comment $commentdata = compact('comment_post_ID', 'comment_author', 'comment_content', 'user_ID'); $comment_id = wp_new_comment( $commentdata );
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:
// check if the comment is approved $comment = get_comment($comment_id); if ($comment->comment_approved==0) wp_die('Your comment is awaiting moderation.');
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:
// return status
die ( 'OK' );
}
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.