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.

Browsers are like Churches

Last night one of my clients asked me why the same code can be interpreted so differently by different browsers. Though I agreed as I pointed out the long standing rift between Internet Explorer and most of the others, I couldn’t really explain why. But after sleeping on it I think I have a decent analogy.

The same text (or scripture) can be interpreted to mean very different things when you go to two different churches, even within the same religion. In the same way, identical html/css text can mean entirely different things when you view it through the window of one browser vs another, even on the same computer.

Yes there are commonalities between churches and across browsers. Many churches even across religions will agree that stealing is not acceptable. Just like many browsers, even across operating systems, will display an error if a requested file is not found.

However, some churches and browsers are more lenient than others in the “grey areas”. For example, certain churches accept alternate lifestyles and others exclude those who participate in them. Internet Explorer (IE) is very strict in it’s adherence to the rules. If an ending div tag is not specified IE shows no mercy, not even a helpful error message. Firefox and Chrome are more focused on the what is “in the heart”, often overlooking minor offenses and sometimes even providing helpful guidance in returning to the right path when mistakes are made.

Some churches provide free services that empower people to change. They run programs for helping people to overcome addictions and live a more fulfilling life. Some browsers like Firefox have free plugins like Firebug and Web Developer which help its users to overcome bad habits and understand how to bring their code to life.

At the end of the day, we are all in this World Wide Web together, no matter which browser we use or which church we go to. Whether online or offline the understanding and acceptance of diversity allows us to thrive while creating and enjoying wonderful experiences. 🙂

How to Add the Sidebar to WordPress Twenty Eleven Theme Single Posts

This is my first post since splitting off my technical posts into a new blog focused in that area. Part of the process was setting up a new wordpress blog, and of course I wanted to try a new theme, the Twenty Eleven theme. After I began importing a few posts I realized that there was no simple option to add the sidebar to the single post view. I tried messing with the CSS for a few minutes and then realized that there must be plenty of answers from people about this issue already.

I found one that looked promising at http://tricksmommy.com/2011/07/08/add-sidebar-in-single-post-pages-of-twenty-eleven-wordpress-theme/. Unfortunately after following the detailed instructions there the single post page had the sidebar added but the main index page was shifted off to the right. I couldn’t figure out the exact reason why, but the instructions mentioned copying css from another view so I figured it must be a different setup or something. I chose the left sidebar on my site whereas they used the default with the sidebar on the right, so that might be why it didn’t work for me. After removing those changes I came up with a simpler solution (step 1 is the same as the site mentioned above, step 2 is where we differ):

  1. Go the the Theme Editor and select the Single Posts(single.php). Search for the following line:
    <?php get_footer(); ?>
    

    Just above it place the following code:

    <?php get_sidebar(); ?>
    
  2. In the same file, look for the following code:
    <?php get_template_part( 'content', 'single' ); ?>
    					
    <?php comments_template( '', true ); ?>
    

    You’ll want to add another div around the above two lines and give it a new class name so you can set the positioning, like this:

    <div class="singlePostWrapper">
    <?php get_template_part( 'content', 'single' ); ?>
    					
    <?php comments_template( '', true ); ?>
    </div>
    
  3. Next you’ll open the style.css and add a simple definition for the new css class you created above as a wrapper around the post and comments on the single post pages. You can add this at the end of the file:
    /*Allow room for sidebar in single posts*/
    .singlePostWrapper {
      position:relative;
      left:25%;
      width:75%;
    }
    

    Note that the above class definition works well for the sidebar on the left, but if you chose to put the sidebar on the right in the theme settings you can change the word ‘left’ above to ‘right’ and it should work fine.