Form Ajax : How to Create and Submit a Form Using Ajax

For the longest time, web developers were stuck submitting their forms in the normal way: Click a button, go to a processing page, redirect back.  However, now it is possible to submit a form without ever leaving the page with Ajax.  Ajax stands for Asynchronous JavaScript, which as stated before, basically means you can submit a form without ever leaving the page.

So how do you use form Ajax? First of all, we’re going use a JavaScript library called jQuery.  Don’t be scared of it though, jQuery makes JavaScript easy.  What jQuery allows us to do is use form Ajax without having to muck around with all the tedious JavaScript details (which trust me, is a GOOD thing).   Without further a due, here is how to submit a form with Ajax.

To download the full working code for this, click here.

Form Ajax Step 1:  The HTML Page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<html>
<head>
<title>Form Ajax Tutorial</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//After the document has loaded, it adds the following handlers
//to the web page.
$(document).ready(function() {
//When the form with id="myform" is submitted...
$("#myform").submit(function() {
     //Send the serialized data to formProcessor.php.
     $.post("formProcessor.php", $("#myform").serialize(),
     //Take our repsonse, and replace whatever is in the "formResponse"
     //div with it.
    function(data) {
          $("#formResponse").html(data);
     }
);
return false;
});
});
</script>
<head>
<body>
<h2&gt;Form Ajax Tutorial</h2>
<p&gt; Fill out some information &lt;/p>
<form id="myform">
<input type="text" name="firstName" value="" /><br />
<input type="text" name="lastName" value="" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<div id="formResponse">
</div>
</body>
</html>

For anyone who is used to HTML programming, this should all look very familiar.  The only confusing part is the JavaScript, but I’ll explain that here.  The first bit just includes the jQuery library.  This is crucial for form ajax to work.  The rest of the function is explained below:

  • $(document).ready() – This will add handlers to your web page only after the entire page has loaded.
  • $().submit() – This will catch the click of the submit button so that it doesn’t submit the form the normal way, but the Ajax way instead.
  • $().post() – This is the part that sends out data to the processing file.  It also has a callback function that will modify our page to contain data that the processing file sent back.
  • $().serialize() – Takes our form data and puts it into an easy to parse format.

Form Ajax Step 2:  The Processing Page

1
2
3
4
5
6
7
8
9
10
11
<?php
//Get the information that was sent from the form.
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
 
//Get the unix time stamp.
$unixTimeStamp = time();
 
//Print output for out web page to catch.
echo "Hello $firstName $lastName.  The local unix time is <b>$unixTimeStamp</b>";
?>

The processing page is very important for making form ajax work correctly.  What this file does is catch the data sent by the form, and then prints out some information.  The form is waiting for this information, and then will add it to your page.  Note:  This file is a .PHP file.  You need to be running a web server (or have access to one) that can process php files.

Form Ajax Step 3:  You’re Done!

Form Ajax used to be pretty difficult, but now that their are JavaScript libraries like jQuery, MooTools, and Scriptaculous, it’s easier than ever.  To download the full working code for this example, click here.

Webmin Virtual Host Not Working? Here’s How To Fix It.

One of the most frustrating experiences when setting up a new web server is trying to get your virtual hosts to work correctly.  The program Webmin is supposed to make this easier, however you’re are often left by Webmin with a virtual host (or hosts) that is not working.  There are a few tell-tale signs that your virtual host files are broken or not working correctly, and the most obvious is that you go to one site, but get another.  For instance, lets say that you have a virtual host set up for apacheWebSite.com and it points to /home/apacheWebSite.com/htdocs.  Now let’s assume you have another virtual host setup for nginxWebSite.com and it points to /home/nginxWebSite.com/htdocs.  Webmin has configured your virtual host wrong if you go to apacheWebSite.com and get nginxWebSite.com’s content (or vice-versa).  To fix it, do the following:

1:  Open /etc/apache2/apache2.conf in the editor of your choice.

2:  Comment out (using ‘#’) or delete the line that says:

# Include the virtual host configurations:
Include /etc/apache2/sites-enabled/

3:  Add the following to the bottom of the same file (substituting your site information) and then follow it as a template for adding more virtual hosts in the future.

#Virtualhosts
<VirtualHost *:80>
DocumentRoot /var/www
</VirtualHost>

<VirtualHost *:80>
DocumentRoot “/home/wrestlingaddix.com/htdocs”
ServerName wrestlingaddix.com
ServerAlias www.wrestlingaddix.com
<Directory “/home/wrestlingaddix.com/htdocs”>
allow from all
Options +Indexes
</Directory>
</VirtualHost>

<VirtualHost *:80>
DocumentRoot “/home/dansbikeshop.org/htdocs/dansbikesWP”
ServerName dansbikeshop.org
ServerAlias www.dansbikeshop.org
<Directory “/home/dansbikeshop.org/htdocs/dansbikesWP”>
allow from all
Options +Indexes
</Directory>
</VirtualHost>

4:  Reload Apache by executing /etc/init.d/apache2 reload.

That’s it!  It’s really much simpler to create the virtual hosts without Webmin.

Javascript Net PDF Viewer

When trying to view PDF files on the internet, you have a very limited number of choices.  The obvious one is to let the user handle viewing PDFs with something like Adobe Acrobat Reader.  However, some users don’t have Acrobat installed.  Or the file gets downloaded instead.  If you want an easy way to view PDF files online though, look no further than Google Docs.

The Google Docs Javascript PDF Viewer will embed the same javascript pdf viewer that Google Docs uses right in to your page via an IFrame.  It’s really that easy.  It even allows for searching of documents (which is quite handy!).  If this sounds like what you’re looking for, the link is below.

Javascript Net PDF Viewer [Google Docs]

How To Restrict Page Access in WordPress

One of the things that is seemingly lacking in WordPress is a way to restrict page access for authenticated users. Sure, you can password protect posts, but what if you want to restrict a page or post to only authenticated users? Or restrict a page or post to only a certain group of people? Without a 3rd party plugin, this isn’t possible.

Enter User Access Manager.  Restrict Page Access WordPress

With the User Access Manager plugin, you can restrict your posts and pages easily with WordPress. It’s a fairly robust plugin, and allows you to create user groups, set access by category, and even limit access to uploaded files. Check out the screen shots below to see it in action.

Restricting Pages in WordPress with User Access Control

Fwds.Me: A Simple URL Shortener

Awhile ago on the internet, there was a big debate going on about the value of URL shortening services like Bit.ly.  I was following the debate with some interested when I decided to create my own URL shortener.  It does only one thing, and that is shorten URLs.  Fwds.Me is still young, so the possibility of getting REALLY short URLs is very real.  If you are looking for a simple url shortener, then look no further than Fwds.Me.

Go To Fwds.Me

How to Enable Multisite in WordPress 3

One of the most touted new features in WordPress 3 is the integration of WordPress MU into the main branch of WordPress.  What this allows you to do is run multiple WordPress sites or blogs, while only needing one install.  The only issue is that this functionality is not enabled by default.

To enable multisite in WordPress 3, you need to add the following line somewhere in wp-config.php. [Note:  Make sure you disable all of your plugins first.] 

define('WP_ALLOW_MULTISITE', true);

After you set WP_ALLOW_MULTISITE to true, you’ll get a new menu item called “Network” under the tools menu.


From there, you can experiment setting up new sites.

Validate Email Addresses With PHP

If you’re a web programmer, there will come a time when you need to validate an email address. It’s going to happen, so just accept it. In newer versions of PHP, there is built in functionality for this. However, for those of us not lucky enough to be running the latest and greatest version, we can use regular expressions.

The following PHP function will validate email addresses using regular expressions. True is returned on success, and false is returned otherwise.

1
2
3
function validate_email($email) {
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email);
}

Simple WordPress Plugin Tutorial

Sometimes WordPress just doesn’t do what you want it to do.  When that happens, you turn to plugins for help.  But sometimes, the WordPress plugin repositories don’t have what you need either.  In those cases, it’s time to pull up your sleeves and get to work.  In this tutorial, I’m going to go through the process of creating a simple WordPress plugin from scratch.  I created this plugin as a proof of concept awhile ago, and thought that it would make a great learning tool now.

Step 1:  What are you’re making anyways?

This plugin does one thing only, and it does it well.  It will place a “Submit to Hacker News” button on all of your posts.  While this tutorial is only for a simple plugin, it could easily be extended to include other news aggregation services and social networks.


Step 2:  Creating the plugin.

Now that we know what we’re going to create, we need to create the plugin.  To do that, simply create a file called wp-hacker-news.php and then add the following to it.

1
2
3
4
5
6
7
8
/*
* Plugin Name: WP Hacker News
* Version: 0.1
* Description: Adds a "Submit to Hacker News" button to your posts.
* Author: Jack Slingerland
* Author URI: http://www.re-cycledair.com/
* Plugin URI: http://www.re-cycledair.com/wp-hacker-news
*/

The lines above are all required for a WordPress plugin to function correctly.  Below is a quick run-through of what each of these means.

  • Plugin Name – This is the name of your plugin.  It is how it will appear in the WordPress back-end administration panels.
  • Version – The version number.  I always start a 0.1 to start, and then increment like 0.1.1 for small changes.
  • Description – This is the description of your plugin.  Feel free to be verbose here, as this is how people will know what your plugin does.
  • Author – This is you!  Put your name or the name of your team here.
  • Author URI – Your website.  In my case, I link it to http://www.re-cycledair.com.
  • Plugin URI – The web page for your plugin.  Here, I’m linking it to the original announcement I made for this plugin.

Step 3:  Creating a display function.

So you finally have a WordPress plugin.  That’s great and all, but it doesn’t do anything yet.  What you need now is to create a  function that displays the “Submit To Hacker News” link.  To do that, add this below the comment section:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Function to show the HN Link.
function WPHackerNews_link() {
     global $post;
     $link = urlencode(get_permalink($post->ID));
     $title = urlencode($post->post_title);
     $formattedLink = "
     <div style="float: right; margin-left: 10px; margin-bottom: 4px;">
          <a href="http://news.ycombinator.com/submitlink?u=$link&t=$title">
               <img src="http://www.re-cycledair.com/wp-content/uploads/2010/03/hn.jpg" alt="" />
          </a>
          <span style="font-size: 9px;">
               <a href="http://news.ycombinator.com/submitlink?u=$link&t=$title">Submit to HN</a>
          </span>
          <a href="http://news.ycombinator.com/submitlink?u=$link&t=$title"></a>
     </div>
";
 
     return $formattedLink;
}

The code above explains itself pretty well.  But I’ll break it down a bit anyways.

  1. We set the global post variable.  It holds all of the information about the post we’re currently on.
  2. Store the current post’s permalink and title in variables.
  3. Using some in-line css and good old HTML, we get the Y Combinator logo to float on the right side of the post.
  4. Return the HTML for the button to the caller of the function.


Step 4:  Displaying your plugin.

Everything is going great, but now we need this to actually show up in posts.  To do that, we register a display function with WordPress.  With a bit of logic, we can make it only display on posts.

1
2
3
4
5
6
7
8
9
10
11
//Integrate with Wordpress.
function WPHackerNews_ContentFilter($content) {
     if(is_single()) {
          return WPHackerNews_link().$content;
     } else {
          return $content;
     }
}
 
//Add the filter
add_filter ('the_content', 'WPHackerNews_ContentFilter');

The above code isn’t self-explanatory at all, so here’s how it works.

  1. When we create the function, we make sure to pass it “$content”.  “$content” is a variable that holds the content of the post that the user is on.
  2. We then check to make sure that we are on a single post with the function “is_single()”.
  3. If so, we return our button by calling “WPHackerNews_link()” and appending “$content” to it.
  4. If not, just return the original un-altered content.
  5. The final step is to use the “add_filter” function to add this plugin into WordPress.  The first argument describes where our plugin should be used (“the_content”), and the second argument is what function it should use (“WPHackerNews_contentFilter”).

Step 5:  You’re Done!

That concludes this tutorial on creating a simple WordPress plugin.  All you need to do now is drop this file in your wp-content/plugins directory and then activate it in the admin.  As usual, if you run in to any errors or notice any problems, please let me know and I’ll help the best I can.