How to Add a Form in a WordPress Post

This is a simple step by step guide to creating a form that will capture data and store it in a mysql database on your server from within a wordpress post

Note: the below example is a live, working form on this page

Step 1:

Create a simple form for a petition, contact request, or registration:

Name:
Address:
City:
State:
Email:
Comment:

Here is the html code for it:

<table>
<tr><th>Name:</th><td><input id="userName" /></td></tr>
<tr><th>Address:</th><td> <input id="userAddress" /></td></tr>
<tr><th>City:</th><td> <input id="userCity" /></td></tr>
<tr><th>State:</th><td> <input id="userState> /></td></tr>
<tr><th>Zip:</th><td> <input id="userZip" /></td></tr>
<tr><th>Email:</th><td> <input id="userEmail" /></td></tr>
<tr><th>Comment:</th><td> <textarea id="userComment" ></textarea></td></tr>
<tr><th><td colspan=2><button type="button" onclick="saveUser();">Save</button></td></tr>
</table>

Step 2:

Create a javascript function to process the form and send it to the server. The following is a javascript function added to the page using the CSS & Javascript Toolbox plugin (it uses jquery because wordpress already has that available):

//Process the form and save the data record
function saveUser() {
  //First gather the form parameters and make sure name and email at least are populated
  var name = jQuery("#userName").val();
  var address = jQuery("#userAddress").val();
  var city = jQuery("#userCity").val();
  var state = jQuery("#userState").val();
  var zip = jQuery("#userZip").val();
  var email = jQuery("#userEmail").val();
  var comment = jQuery("#userComment").val();
  if (name.length<1 || email.length<1) {
    alert("Please at least enter your name and email.");
    return false;
  } else {
    //Now send the data to a server side function to really validate it and save it.
    jQuery.ajax({
      type: "POST",
      url: "/ajax/saveUser.php",
      data: { name:name,address:address,city:city,state:state,zip:zip,email:email,comment:comment }
    }).done(function( results ) {
      if(results.length<1){ // network error
        alert("There was a network error, please try again or contact support and tell them what you are trying to do.");
      } else { // this is a successful interaction
        var resultObj = jQuery.parseJSON(results);
                
        if (resultObj.errorMsg.length>0) {  
          alert(resultObj.errorMsg);
        } else {
    	  //Record save successful
          alert("Thanks for your information, it was saved successfully!");
          //Show the user what they have entered:
          jQuery("#userList").html(resultObj.userList);
        }
      }
    });
  }
}

Step 3:

Make sure you have a database table ready to store the information. Below is a simple table used to store the info in this example:

CREATE TABLE IF NOT EXISTS `user_info` (
  `userID` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(80) DEFAULT NULL,
  `address` varchar(100) DEFAULT NULL,
  `city` varchar(80) DEFAULT NULL,
  `state` varchar(40) DEFAULT NULL,
  `zip` varchar(5) DEFAULT NULL,
  `email` varchar(80) DEFAULT NULL,
  `comment` text DEFAULT NULL,
  `userIP` VARCHAR( 30 ) DEFAULT NULL,
  `dateAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`userID`),
  KEY `userIP` (`userIP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step 4:

Create the server side code to accept the form data, really validate it, and put it in the database or send back an error. Here is the contents of a server side code which will do all that for the example data above. Since this form is “in the wild”, I’m capturing the IP address because I will only show results to people that they entered themselves:

/*
 * File: saveUser.php
 * Description: This file takes the passed in user information and validates it before
 * 	saving it to the database and returning content to show on the page. 
 * Inputs (in POST): 
 * 	userName, address, city, state, zip, email, comment
 * Outputs:
 * 	either an error or nothing
 */
include("db.php"); // define your database credentials in another file

#connect to the database
$db = mysqli_connect($servername, $username, $password, $dbname);
mysqli_select_db($db,$dbname) or die('Could not select database');

#Get the passed in parameters into local variables, escaped for database input
$userName = empty($_POST['userName'])?'':addslashes($_POST['userName']);
$address = empty($_POST['address'])?'':addslashes($_POST['address']);
$city = empty($_POST['city'])?'':addslashes($_POST['city']);
$state = empty($_POST['state'])?'':addslashes($_POST['state']);
//only accept 5 numbers for zip
$zip = empty($_POST['zip'])?'':substr(preg_replace('/\D/','',$_POST['zip']),0,5);
$email = empty($_POST['email'])?'':addslashes($_POST['email']);
$comment = empty($_POST['comment'])?'':addslashes($_POST['comment']);
$userIP = $_SERVER['REMOTE_ADDR'];

#This is an array used for gathering all the outputs of this file
$jsonObj = array();
$jsonObj['errorMsg'] = "";
$debug=false;

#Validate inputs
if (empty($userName) or empty($email)) {
	$jsonObj['errorMsg'] = "Please at least enter your name and email.";
} else if (strpos($email,'@')===false) {
	//there are many more validations that can be made for emails but this is a start
	$jsonObj['errorMsg'] = "Please enter a valid email.";
}

#Enter the data record
if (empty($jsonObj['errorMsg'])) {	
	$sql = "insert into user_info (userName,address,city,state,zip,email,comment,userIP) 
			values
			('".$userName."','".$address."','".$city."','".$state."','".$zip."','".$email."',
			'".$comment."','".$userIP."')";
	if ($debug) echo "about to run $sql ";
	mysqli_query($db, $sql); $err = mysqli_error($db); if (!empty($err)) $jsonObj['errorMsg'] = $err;
}

#Now get the list of data entered by this IP, without any script tags to prevent XSS:
$jsonObj['userList']='';
if (empty($jsonObj['errorMsg'])) {	
	$sql = "select userName,city,state from user_info where userIP='".$userIP."'";
	$rs = mysqli_query($db, $sql); $err = mysqli_error($db); if (!empty($err)) $jsonObj['errorMsg'] = $err;
	while($row = mysqli_fetch_assoc($rs)) {
		$jsonObj['userList'].= "<tr><td>".strip_tags($row['userName'])."</td><td>".strip_tags($row['city']).
				"</td><td>".strip_tags($row['state'])."</td></tr>";
	}
}

#Now send back the data in json format
echo json_encode($jsonObj);

Step 5:

Do something with the results! You could export them, feed them into another system using an API, send them in an email to someone, or just display them like so:

Name City State
You have not entered any user records yet, try it out!

How to use Ajax in a WordPress Post

I recently put together an Ajax autocomplete example using PHP and Mysql so I could post it on my blog, but after getting it working outside wordpress on an independent page I had trouble getting it into wordpress.

I had used plugins in the past which allowed for php code to be used with shortcodes, but inline javascript calls are not something I had gotten past the wordpress editor before. The php code used for retrieving data from the database is in a separate file so no shortcode is needed for that portion.

The inclusion of the javascript autosuggest functions is something I first tried putting in a code block in the wordpress post itself as a link to the external file (autosuggest.js), but unfortunately that didn’t work. Then I saw an article where someone suggested putting the javascript in the theme file header.php and surround it with a php if statement checking for the specific post you want it to appear on. I tried that but later removed it because I wanted my ajax to work on the index page, archive pages, and category/tag/author pages – not just the “single post” page.

Then I went back to the plugin I had installed (CSS & JavaScript Toolbox) for css and javascript and tried putting the entire contents of the autosuggest.js file into one javascript block and installing that in the footer. That worked perfectly so I did the same thing for the css file using the same plugin.

The next challenge was to add the inline JavaScript (ajax) function calls from within the html code for the sample input box in the wordpress post. When I tried just putting it all into the html editor for wordpress the javascript was removed. This was not just a snippet of complete javascript or css though, so I couldn’t just use the same plugin to make another code block and put it in the header or footer.

Since PHP is executed as the page loads, I figured I could put my auto-complete input box with ajax call into a php shortcode and put the shortcode where I wanted the input box to be in my html code. That way wordpress would not filter out the javascript when saving the post contents to the database because it would be hidden behind a shortcode which would be replaced during page loading.

This worked beatifully, including the inline javascript by putting it inside a php shortcode. I used the Shortcode Exec PHP plugin for this, which is very easy to work with.

Simple Ajax Auto-Complete Example

In a previous post I wrote about how I learned ajax quickly, but recently I learned that the main link I learned from is no longer valid. So I decided to make a simple example I could host myself. Along the way I learned that it is not trivial to include ajax within a wordpress page, but I wrote another post about how I figured that out. 🙂

The input box below is enabled with auto-complete using a simple ajax example. The javascript can be seen here, the css can be seen here, and the php ajax function can be seen here. The input box below calls the getScriptPage javascript function if there are at least 2 characters present. That javascript function calls the php ajax function using a server request. The text sent back from the server by the php file is then handled by the handleHttpResponse javascript function, which just populates a hidden div with choices. The getScriptPage function makes that hidden div (with an id of “box”) visible if the response from the php ajax call is not empty.

The database table being queried has 1000 rows in it, in the following format: name100 (where 100 is the number of the record, 1-1000). So if you start typing “name” in the box, after na you will start seeing 5 suggestions below. If you keep typing the suggestions will be updated as you type.

HTML code for input box

<div id="headersearch">
	<div id="searchbar">
		<div class="ajax-div">
			<div class="input-div">
			<input type="text" autocomplete="off" onKeyUp="if(this.value.length>1) 
				getScriptPage('box','searchTerm','http://www.wilycode.com/'); else box(0);" 
				name="searchTerm" value="Enter Name Here" onClick="if(this.value.substr(0,6)=='Enter ') this.value=''"
				id="searchTerm" onBlur="if(this.value.length<1) this.value='Enter Name Here'">
			</div>
			<div id="box"></div>
		</div>
	</div>
</div>

April 24th 2014 Update:

I was asked to add arrow navigation to an autosuggestion box I created this week using the method described above, and found that there are easier ways to do this. I found that jquery UI has an autocomplete widget which can be used to enable arrow key navigation among many other features. However I had trouble getting the examples at api.jqueryui.com/autocomplete/#entry-examples to work, so I did some more searching and found a step by step implementation using a php file for the source element of the autocomplete function which I was able to get working pretty easily, at www.pontikis.net/blog/jquery-ui-autocomplete-step-by-step.

The Essence of AJAX – How I learned it in an hour

originally posted at http://www.goodfeelingplace.com/the-essence-of-ajax-how-i-learned-it-in-an-hour
I was a bit resistant to learning ajax for a couple years because I didn’t see a need for it in the programs I was developing.  However, one day I learned it without knowing it.  I was working with code written by someone else which called a javascript function that invoked a url, then called another function to handle the results of the url.  An example that looks very similar to the code I was working with is at http://www.captain.at/howto-ajax-form-post-request.php (unfortunately that page no longer exists, but I’ve made my own example that you can see at http://www.wilycode.com/simple-ajax-auto-complete-example/ – the details below refer to the not found page but the concepts are the same).

If you look at that code, there are 3 javascript functions used – get (this is called from clicking on a button in the form on the page), makePostRequest (this is the function which calls the url and sends parameters to it via the post method), and alertContents (this function is called from the makePostRequest function when the response is received from the url).

The get function just creates a string with parameters to pass, defines an url, and then passes them to the makePostRequest function.  Here are the main lines of code in the makePostRequest function and what they mean:

  • http_request.onreadystatechange = alertContents; – this says when the http_request.readyState changes, then call the alertContents function.
  • http_request.open(‘POST’, url, true); – this defines what url is going to be called and what method is going to be used
  • http_request.send(parameters); – this sends the parameters specified in the post array to the url requested

There are a few other lines specifying a the header of the request, and a bunch of lines in the beginning that setup the http_request object to work for different browsers.

Then in the alertContents function (which is actually called several times, whenever the readyState changes), once the readyState of 4 is reached (you can read more about readyStates at http://www.yaldex.com/wAjax/DiggingdeeperintoHTTPreadystates.html) the http status is checked.  If the status is 200 (and not 404, 501, 301, etc. – see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a full list with explanations) then the result of that http request (like what you would get if you put that url into a browser address bar and sent the appropriate post parameters in the header – done through a script, not a browser – then checked the page source) is stored into a javascript variable and you can do whatever you want with it.

In that example they just stick it into a span element on the existing page, but you can do many other things.  If you invoke an url which takes as parameters the values of certain form elements on the page, you could return a list of values to populate another dropdown with, etc.  So you can take the example and modify the parameters passed, what the invoked url does, and what is done with the results – then you will have your own ajax function!