About Me

Featured

Hi! I’m Wern Ancheta. I’m a Web Developer from San Fernando City, La Union, Philippines. I love building things for the web and sharing the things that I’ve learned through writing. When I’m not coding or learning something new, I enjoy watching anime and playing video games.

Services Offered

Here are some of the services that I normally offer:

  • Web Development – mainly PHP and its Frameworks (CodeIgniter, Laravel, Flight).
  • System Analysis and Design – from requirements analysis, database design, to system architecture design.
    Note that this is what I do most of the time. But I also work with JavaScript (NodeJS), Ruby, and WordPress projects from time to time.

If you have an interesting project or an idea that you want to implement please contact me:

  • Email
  • skype name: wernancheta

Elsewhere

Donation

If you like this blog and you want to say thanks please consider making a donation. I’d really appreciate it.

Advertisements

Updates

Its been 2 months since I last published a tutorial on this blog since I was publishing on my Octopress blog hosted by github at http://anchetawern.github.com.  I noticed that non of my entries were on the first page of Google search which means that I was not getting any eyeballs on my blog. Though I don’t really care if anyone is reading my blog because I’m just doing this because I want to. But I atleast want it to be reachable by people who are looking for solutions that I might have already tackled in one of my blog entries before so that I can hit atleast 2 birds with one stone ( learning more about something by teaching it and helping other people through writing tutorials and solutions to problems that I have encountered). And for this purpose WordPress is pretty much the wise choice. Most WordPress blogs are high quality blogs therefore they’re mostly stay on the first page of Google search results. So I’m going to continue publishing tutorials in this blog in the next couple of weeks as I’m still figuring out how to create something that would allow me to convert some of the markdown files from my Octopress blog to HTML. I’m planning to republish the tutorials that I’ve published on my Octopress blog to this blog. And of course I’ll still continue publishing the weekly link dumps.

Transferring to Octopress

I recently transferred from my other WordPress blog(Data Integrated Entity) to this one. But now I hate to say this but I’m going to transfer again into an Octopress blog which is hosted at Github through the power of Github pages.
But it doesn’t mean that I’m going to stop posting stuff in this one. I’m still going to post at least once a week but its not your usual tutorials because that’s what I plan to put on my new blog. So instead of tutorials I’m going to share my reading list (things that I have read or want to read later on). I won’t probably include a descriptive text so I’m just going to post the links.

I’ll also occassionaly post stuff in here if I feel like it.

And if you’re interested in discovering the lighter side of me then visit my tumblr blog or follow me on twitter.

Thanks!

Performing ajax calls with jQuery, Dojo and Mootools

Introduction

In this tutorial we are going to look at how to perform ajax calls in the three of the most
popular JavaScript libraries out there: jQuery, Mootools, and Dojo.
First were going to look at how to perform simple ajax request using the POST and GET methods.
Next were going to submit forms using ajax.
Lastly we are going to submit and retrieve data using JSON.
Of course I’m going to show you how to do this in jQuery, Mootools, and Dojo.
Were going to use PHP for the backend as its the most popular server-side language at the time of writing
of this article. But if you’re a rubyist or a pythonista and want to learn ajax then worry not, most
of the PHP code that I used in this article are very simple and it should be easy to port them
into the language of your choice.
At the end of this article you will have an idea how each of these libraries handle
ajax calls.
So yeah let’s get started.

Including the Libraries

First let’s look at how they do things in jQuery. But to make sure nobody is left behind let’s first include the libraries that were going to use: jQuery, Mootools and Dojo:


		<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
		<script src="http://mootools.net/download/get/mootools-core-1.4.5-full-nocompat.js"></script>
		<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/dojo/dojo.js"></script>

	

You might be aware that jQuery and Mootools are both using dollar sign($) as an alias and this creates a conflict when you include the 2 libraries in the same page. Here’s a very good article from David Walsh on how to use jQuery and Mootools together:
Using jQuery and MooTools Together

Always remember to include your scripts after your html, preferably after the body tag as mentioned in this article from yahoo:
Best Practices for Speeding Up Your Website

jQuery $.post

Once you’re done with that create a new PHP file. This will be the file that were gonna be talking to in the backend using ajax.

Going back to our main file (the file in which we linked to jQuery) we create a new object called names and an array called letters:

		var names = {
			name: 'cool',
			names: ['pizza','coffee','milk','c2']
		}

		var letters = ['abc','def','ghi'];
		

Next we submit it using the $.post method which requires one argument and two optional arguments. First is the name of the file in the server that we want to talk to (ajaxback.php), second is the collection of data that we want to submit to that file, third is the callback function in which we specify what we want to do after the the call has been made. Just like when making a phone call, first you must have someone to call which is defined by the phone number of the person that you’re going to call, second you must have things to talk about, third what you want to do once you’ve said everything that you want to say.

		$.post('ajaxback.php', {'names' : names, 'letters' : letters}, function(data){

			console.log(data); //output what's returned by ajaxback.php
		
		});
		

Dojo xhrPost

The dojo equivalent of the $.post method in jQuery is the xhrPost method which requires three properties. First is the url which is the file in the backend in which you want to submit data, second is the content in which you can simply specify an object(key-value pair), and then the load in which you specify a function to be executed once the ajax call has been made.

		dojo.xhrPost({
			url: "ajaxback.php",
			content: {'names' : names, 'letters' : letters},
			load: function(data){
				console.log(data);
			}
		});
		

Mootools POST Request

The same thing can be done using mootools by creating a new instance of the Request class which has pretty much the same options as the xhrPost in dojo.
The method which is basically the method that you’re going to use to submit the data in this case were using POST.
Next is the url which is pretty much the same as the url property in xhrPost, there’s also onComplete in which you specify a function that will be executed once the ajax call is completed. Finally you need to call the send() method to send the request into the backend.

	
		var post_req = new Request({
			method: 'POST',
			url: 'ajaxback.php',
			data: {'names' : names, 'letters' : letters},
			onComplete: function(data){
				console.log(data);
			}
		}).send();
		

Accessing data submitted via POST in the backend

For our PHP file(ajaxback.php) we simply output everything that has been submitted via the $.post method in jQuery:

		<?php
			//output everything submitted via POST method
			print_r($_POST); 
		?>
		

jQuery $.get

We can also submit data using the $.get method which works pretty much like the $.post method but the only difference is that it submits the data using the GET method. Here’s how:

			$.get('ajaxback.php', {'name' : 'son gohan', 'technique' : 'awesome'}, function(data){
				console.log(data);
			});
		

Dojo xhrGet

The Dojo equivalent of $.get in jQuery is the xhrGet method

		dojo.xhrGet({
			url : "ajaxback.php", 
			content : {'name' : 'son gohan', 'technique' : 'awesome'},
			load : function(data){
				console.log(data);
			}
		});
		

Mootools GET Request

The same thing can be done in Mootools by just changing the method option to GET.

		var gets = new Request({
			method: 'GET',
			url: 'ajaxback.php',
			data: {'name' : 'son gohan', 'technique' : 'awesome'},
			onComplete: function(data){
				console.log(data);
			}
		}).send();
		

Accessing data submitted via POST in PHP

There’s not much of a difference except that if you have to access the data in the backend you will no longer use the $_POST you will use $_GET instead:

		<?php
			echo "name: " . $_GET['name']."\n";
			echo "technique: ". $_GET['technique']."\n";
		?>
		

Submitting Data with both POST and GET in jQuery

But you can also submit data using both POST and GET methods here’s how:

		$.post(
				'fakepost.php?name=songoku&technique=kamehamewave', 
				{'name' : 'son gohan', 'technique' : 'awesome'}, 
				function(data){
					console.log(data);
				}
		);
		

In the example above we still used the $.post method for submitting the data
but we appended a query string in the url(name=songoku&technique=kamehamewave), this query string is submitted via the GET method but the key-value pair that we used in the data part will still be submitted via POST method.

Submitting Data with both POST and GET in Dojo

Of course we can also do the same trick in dojo.

		dojo.xhrPost({
			url : "fakepost.php?name=songoku&technique=kamehamewave",
			content : {'name' : 'son gohan', 'technique' : 'awesome'},
			load : function(data){
				console.log(data);
			}
		});
		

Submitting Data with both POST and GET in Mootools

The same thing can be done in Mootools by simply passing in a query string after the url and then specifying a key-value pair on the data option:

		var gets = new Request({
			method: 'POST',
			url: 'gets.php?name=songoku&technique=kamehamewave',
			data: {'name' : 'son gohan', 'technique' : 'awesome'},
			onComplete: function(data){
				console.log(data);
			}
		}).send();
		

Accessing data submitted via POST and GET in PHP

We can then access it in PHP(fakepost.php) using both $_POST and $_GET:

		echo "Im accessed via GET method\n";
		echo "name: " . $_GET['name']."\n";
		echo "technique: ". $_GET['technique']."\n\n";

		//Accessing data using $_POST method
		echo "Im accessed via POST method:\n";
		echo "name: " . $_POST['name']."\n";
		echo "technique: ". $_POST['technique']."\n";
		

Updating DOM with AJAX content in jQuery

Next thing that I’m going to show you is how to load the data returned from the backend into the DOM. In other words updating the contents of an existing element in the DOM.
We can do it by simply applying our knowledge in jQuery and use the $.post and $.get methods like this:

			<div id="container">
				
			</div>

			<script>
			$.post('load.php', {'name' : 'picollo', 'age' : 44}, function(data){
				$('#container').html(data); //load the data into the div with the id of container
			});
			</script>
		

As you can see from the code above we simply set the html(the same as innerHTML in plain JavaScript) to the data returned from the backend.


We can pretty much live by just doing that but jQuery has methods created specifically for loading or updating the contents of an existing element. One of such methods is the $.load method which is also very similar to the $.post and $.get methods. You just need to call it from the element where you want to load the new content, the arguments that it requires is pretty much the same with $.post and $.get. Here’s how to use it:

		<div id="container">
				
		</div>

		<script>
		$('#container').load('load.php', {'name' : 'picollo', 'age' : 44});
		</script>	
		

The code above does the same thing as our previous example except that we cut the lines of code from 3 lines to just 1 line (excluding the html code).

Updating DOM with AJAX content in Dojo

We can also do this in Dojo by using either xhrPost or xhrGet. All you have to do is to set the innerHTML of the element that you’re trying to update equal to the data returned from the backend.

		var string_json = JSON.stringify(obj);
		dojo.xhrPost({
			url : "load.php",
			content : {'name' : 'picollo', 'age' : 44},
			load : function(data){
				dojo.byId('container').innerHTML = data; //update contents of container
				/*
				you can also do this by using a native Dojo helper method
				dojo.html.set(dojo.byId('container'), data);
				*/
			}
		});
		

Updating DOM with AJAX content in Mootools

We can do the same thing in Mootools using the set helper method to set the html of the element that were trying to update after the request has been completed.
In this case the div with the id of container.

		var req = new Request({
			method: 'POST', 
			url: 'load.php',
			data: {'name' : 'picollo', 'age' : 44}, 
			onComplete: function(data){
				$('container').set('html', data); //update contents of container
			}
		}).send();
		

And for our backend we simply output what has been submitted via $.post method. This will then be loaded into the div with the id of container as you have seen from the code above:

		<?php
			echo "Name: ". $_POST['name']. "<br/>";
			echo "Age: ".$_POST['age'];
		?>
		

Using $.ajax in jQuery

The $.post and $.get methods are just convenience methods. Methods that were created for the convenience of our poor little fingers. If you want more options like disabling the cache, specifying the content type, data type, specifying error or success callbacks then what you need is the BIG Mama the $.ajax method. Everything you need to know about the $.ajax method is in the jQuery documentation but I’m gonna show you an example of how to do things to get you started.

Here’s how to use the $.ajax method in simplest terms:

		$.ajax({
			type: 'POST', //method for submitting: either GET or POST
			url: 'ajaxback.php', //file in the backend that you're talking to
			data: {'names' : names}, //data to submit
			success: function(data){ //what you want to do once the data is submitted
				console.log(data); //output what's returned by ajaxback.php
			}
		});
		

Using the $.ajax method you can also specify things like the cache and statusCode.
Cache if you want to cache the page that you’ve specified in the url then use true as its value,
if its a page thats constantly updated then use false.

StatusCode is useful if you’re performing ajax calls on a different domain because the page that you’re referring to might not always be available maybe they’re doing a maintenance on the server. Here’s how to use it:

			statusCode:{
				404:function(){
					//what you want to do if the page you're referencing is not found
				},
				403:function(){
					//what you want to do if page is forbidden
				}
			}
		

If you want to know more about status codes then visit this link: Status Codes

AJAX in Dojo

xhrGet and xhrPost in Dojo are pretty much the equivalent of $.ajax method in jQuery since there’s already a bunch of options that you can use like the form in which you simply specify the form that you will use as a data source by using dojo.byId(‘idOfTheFormToUse’), there’s also load option in which you can define the function that you want to execute when the request has been successfully made, there’s also the error option in which you can specify a function that will execute when the request failed, there’s also handle option which let’s you define a function that executes whether or not the request suceeded.

AJAX in Mootools

The Request class in Mootools is already fully packed with options that you can use to customize how you send ajax requests to the backend.
There’s a bunch of options that you can use here’s the documentation

JSON as a data source

Next I’m going to show you how to retrieve JSON from the backend to do that create a new php file(json.php) this will serve as our data source. In the code below were simply creating a new array called $things which has a collection of blogs and people in it. Then we just convert it to JSON string using the json_encode() method
Note that in the code below were using PHP5.4 syntax in defining the array. So we won’t have to switch from JavaScript to PHP minds when defining arrays.

		<?php
		$things = [
					'blogs'=>['smashing magazine', 'codrops', 'sixrevisions', 'nettuts', 'coding horror'],
					'people'=>['john resig', 'jeffrey way', 'chris coyier', 'paul irish']
				];
		/*for PHP5.3 and below
		$things = array(
			"blogs"=>array("smashing magazine", "codrops", "sixrevisions", "nettuts", "coding horror"),
			"people"=>array("john resig", "jeffrey way", "chris coyier", "paul irish")
		);	
		*/		
		$json_things = json_encode($things); //convert array to json string
		echo $json_things; 
		?>
		

Retrieving JSON in jQuery

Next I’m going to show you how to retrieve JSON from the backend and output them in the console.
Were going to use $.post for this one. Note that were expecting a JSON string from the backend.

		$.post('json.php', function(data){
			
			var json_data = JSON.parse(data); //convert JSON string into object
			
			console.log("Awesome Blogs: \n");
			for(var blog in json_data.blogs){ //loop through the blogs
				console.log(json_data.blogs[blog]);
			}
			
			
			console.log("\nAwesome People: \n");
			for(var awesome in json_data.people){ //loop through the awesome people
				console.log(json_data.people[awesome]);
			}
		});
		

Retrieving JSON in Dojo

We can do the same thing in Dojo by specifying JSON as the value for the handleAs option.
This is the same as doing JSON.parse(data) when using plain JavaScript:

		dojo.xhrPost({
			url : "json.php",
			handleAs : "json", 
			load: function(data){
				dojo.forEach(data.blogs, function(row){//loop through the blogs
					console.log(row);
				});

				dojo.forEach(data.people, function(row){//loop through the awesome people
					console.log(row);
				});
			}
		});
		

Retrieving JSON in Mootools

The same thing can be done in Mootools but instead of just creating a new instance of the Request class
we use Request.JSON which automates receiving of JavaScript Objects in JSON format.
We can then use Object.each to loop through
the object.

		var json_req = new Request.JSON({
			url : 'json.php',
			onSuccess : function(json_obj, json_string){//json_obj is the object representation of the json_string
				console.log(json_obj); //this returns an object

				//loop throug the contents of the object	
				Object.each(json_obj.blogs, function(value, key){
					console.log(value);
				});
			}
		}).send();
		

Submit Form via AJAX in jQuery

Finally I’m going to show you how to submit a form via ajax. For that were gonna need a sample form.
The first form(form_sample) is a simple form which has only text fields in it. The second form(form_another)
is also a pretty simple form but were using it to submit an array(notice the name attribute of the fields has open and close brackets after the actual name of the field).

		<form id="form_sample">
			<p>
				<label for="name">Name:</label>
				<input type="text" name="one_name" id="one_name" value="hisoka">
			</p>
			<p>
				<label for="language">Language:</label>
				<input type="text" name="one_language" id="language" value="japanese">
			</p>
		</form>

		<form id="form_another">
			<p>
				<label for="name">Name:</label>
				<input type="text" name="name[]" id="name1" value="killua">
			</p>
			<p>
				<label for="name">Name:</label>
				<input type="text" name="name[]" id="name2" value="irvine">
			</p>
			<p>
				<label for="name">Name:</label>
				<input type="text" name="name[]" id="name3" value="vahn">
			</p>
		</form>
		

For jQuery were simply going to serialize the form using the $.serialize method which simply converts the form to its query string representation(name-value pair separated by &). All you need to do is to call serialize() on the element that you want to serialize, in this case the form_sample which we select by using its id:

		var form = $('#form_sample').serialize();
		console.log(form);
		/*
		output:
		one_name=hisoka&language=japanese
		*/
		

After serializing the form we simply submit it via the $.ajax method:

		$.ajax({
			type : "POST",
			url : "submitform.php",
			data : form, //name of the serialize form
			success: function(data){
				console.log(data); //output what's returned from submitform.php
			}
		});
		

Submit Form via AJAX in Dojo

In dojo we can pretty much submit a form via ajax in just one step, we simply need to specify a value for the form property no need to serialize the form:

		dojo.xhrPost({
			url : "submitform.php",
			form : dojo.byId("form_sample"), //get form by its id
			load : function(data){
				console.log(data); 
			}
		});
		

Submit Form via AJAX in Mootools

We can do the same thing in Mootools by using toQueryString() method which simply converts a form into a query string which is pretty much the same with the serialize() method in jQuery.

		//toQueryString returns: "one_name=hisoka&one_language=japanese"
		//parseQueryString returns the object representation of the query string
		var form_data = $('form_sample').toQueryString().parseQueryString();

		var form = new Request({
			method : 'POST',
			url : 'submitform.php',
			data : form_data, 
			onComplete : function(data){
				console.log(data);
			}
		}).send();
		

You can then access the submitted data in the backend:

		<?php
		echo "Name: ".$_POST['one_name']. "\n";
		echo "Language: ".$_POST['one_language'];
		?>
		

Submit Array Form via AJAX in jQuery

Next we try to submit the other form(form_another) as you can see from the code below the output when we call serialize from it is a little bit different from the sample_form, more like bizzare I guess that’s why I did a quick Google search and found out that it’s called percent encoding it’s pretty much the way how space, open bracket, and close bracket are represented via url encoding:

		var another_form = $('#form_another').serialize();
		/*
		output:
		name%5B%5D=killua&name%5B%5D=irvine&name%5B%5D=vahn
		*/
		

Simply submit it the usual way:

		$.ajax({
			type : "POST",
			url : "submitform.php",
			data : another_form, //name of the serialize form
			success: function(data){
				console.log(data); //output what's returned from submitform.php
			}
		});
		

Submit Array Form via AJAX in Dojo

For dojo we simply repeat what we did earlier for the first form(form_sample), select the form via id and specify it as the value for the form property:

		dojo.xhrPost({
			url : "submitform.php",
			form : dojo.byId("form_another"), //get form by its id
			load : function(data){
				console.log(data);
			}
			error : function(){
				//just in case you're unlucky and your ajax request/call didn't suceed the code here will be executed
			}
		});
		

Submit Array Form via AJAX in Mootools

Submitting the other form(form_another) is pretty much the same with Mootools.

		//toQueryString returns: "name%5B%5D=killua&name%5B%5D=irvine&name%5B%5D=vahn"
		//parseQueryString returns the object representation of the query string
		var form_data = $('another_form').toQueryString().parseQueryString();

		var form = new Request({
			method : 'POST',
			url : 'submitform.php',
			data : form_data, 
			onComplete : function(data){
				console.log(data);
			}
		}).send();
		

You can then access it in the backend(submitform.php) by looping through the contents of $_POST[‘name’] where name is the name of the field that was repeated(name=”name[]”).

		<?php
		foreach($_POST['name'] as $row){
			echo "\t".$row."\n";
		}
		?> 
		

Conclusion

We’ve only scratch the surface of performing ajax calls in jQuery, Mootools and Dojo in this article but hopefully I was able to give you a good introduction so that you can start using them with ease and be able to further your knowledge in this topic. I was also able to gain a fair amount of knowledge as I was researching these. If you have any questions or if you have notice something that is incorrect in this article feel free to share them in the comments as we are all both learning. You can hit the links in the resources if you want to learn more about doing ajax in each of the libraries discussed in this article. Thank you!

Resources

Easy Templating with Mustache.js

Introduction

Any web development dude who is worth their salt would say to you
that you have to separate presentation code from logic code. That’s
why MVC, templating , MVP, MVVM and other acronyms where created.
Why separate presentation and logic?
To make code more maintainable and pleasing to the eyes of the
poor soul whose reading your code. Here’s an example of code that doesn’t use
templating:


var anime = {
	'cool' : [
		'onepiece','k-on','bleach','naruto','hanasaku iroha','star driver','yuru yuri','a channel','tari tari','sword art online','durarara'
	]
};
var parent = $('#no_templates'); //get the element where we are going to append things
var h1 = $('<h1>').text('Without templating'); //create a header
var ul = $('<ul>'); //create a ul element

h1.appendTo(parent); //append header to the no_templates div
ul.appendTo(parent); //append ul to the no_templates div

for(var x in anime.cool){
//append list item into the list
var li = $('<li>').text(anime.cool[x]).appendTo(ul);
}

What the code above does is simply to loop over a list cool anime and append each of them in an onordered list.
Ugly isn’t it?

In this tutorial I’m going to introduce to you a templating library
called Mustache. Mustache is available in
a variety of languages including PHP, Ruby, Python, Clojure, Node.js, ActionScript, and of course
JavaScript which is the flavor that were gonna be using today.

So yeah, go ahead and download Mustache.js from Github then include it into your page. As you might have noticed from the code a moment ago
I also used jQuery to make the code shorter and easier to write. So if you don’t have it yet you can either go to the jQuery site and download your copy or select jQuery 1.7.1 from this site. Later versions might also work.


<script type="text/javascript" src="mustache.js"></script><!--include mustache-->
<script type="text/javascript" src="jquery171.js"></script><!--include jQuery-->

Playing


Basics

To use mustache you must have a data source. This can be an array, a JSON string, a variable. Pretty much these are all objects in JavaScript so I’ll just go ahead and use the term object as a data source for mustache. Another thing that you’re going to need is a template which is basically HTML code where you specify how your data will be rendered in the page. For example if you want something to be displayed as a header the template is where you do it.
Lastly, you’re going to need an HTML element where you want to show your data.
That is all you need when using mustache. A data source , a template, and an HTML element where you want to show your data. Here’s an example:


<script type="text/javascript">
//define an object
var obj = {
		search : 'google',
		sites : ['google', 'twitter', 'facebook']
	};

var template = "<h1>Search Engine:{{search}}</h1>"; //define the template
var html = Mustache.to_html(template, obj); //put the data into the template
$('#container').html(html); //update the container div

</script>
<div id="container"></div>
<pre>

For your template code you just need to place the name of the property that you want to output in a specific tag. In this case the name of the property is search with the value of google. The value is the one that’s going to be rendered inside your template. So the code above will output the word google inside h1 tags.

Next I’m going to show you how to use sections. In programming terms sections are similar to the repeated portion of a loop. In sections we specify a start and an end and the portion that goes between the start and end is the repeated part based on the value of the current item. Here’s how to define a section (were using the same object from earlier):


var template = "<ul>{{#sites}}<li>{{.}}</li>{{/sites}}</ul>"; 

var html = Mustache.to_html(template, obj); //put the data into the template
$('#container').html(html); //update the container div

Let’s break it down. {{#sites}} define the start of the section {{/sites}} define its end. So the pound sign(#) defines the start and the forward-slash(/) defines the end. In between we put some
li tags because they’re basically repeated. Just remember that anything that is supposed to be repeated goes inside the section definition. Lastly we have this weird double mustache with a dot inside ({{.}}) which simply refers to the current item in the list.

Going Deeper


A cleaner way of writing templates

Were done with the basics now let’s try to go deeper. If you think defining templates this way is still ugly you’re not alone I think it’s also ugly. You might have notice that you can’t also go another line when defining templates like we did earlier. You’ll get a nasty error and you need to use plus(+) symbols to append stuff if your template becomes longer than the Golden Gate bridge.


var template = "<ul>{{#sites}}<li>{{.}}</li>{{/sites}}</ul>";

Well good news for you since there’s actually another way of defining a template all you have to do is to place your template inside tags but with the
type of text/html instead of the usual text/javascript which we don’t even need when using html5. Here’s an example:

<script id="anime" type="text/html">
<ul>
	{{#watched}}
	<li>{{.}}</li>
	{{/watched}}
</ul>
</script>

And there’s a bit difference in the code for assigning the data source into the template. Examine the code below:

<script type="text/javascript">
var anime = {
			'watched' : [
						'onepiece','k-on','bleach','naruto',
						'hanasaku iroha','star driver','yuru yuri',
						'a channel','tari tari','sword art online','durarara'
			]
		};

var html = Mustache.to_html($('#anime').html(), anime);
$('#container').html(html);
</script>

<div id="container"></div>

As you might have notice we changed this part of the code to use the template that we have created earlier. All you have to do is to select it using a css selector in this case were selecting the template with the id of anime.

var html = Mustache.to_html($('#anime').html(), anime);


A different structure for data source

Were fine with how the data source is structured so far. But what if our data source is structured in a different way? In some cases we have to deal with data coming from other websites like twitter or facebook for displaying tweets or status updates from users. Data is not always structured the way we like it. In this part I’ll try to walk you through some of ways in which data can be structured and show you how to place them in our mustache templates.
As you can see from the code below we have some repeated properties in our object. This will affect the way on how we will access them on our template later on.

<script type="text/javascript">
var ind = {
	'people' : [
		{'name' : 'kyoya', 'age' : 20, 'dialect' : 'kansai'},
		{'name' : 'pedro', 'age' : 30, 'dialect' : 'tagalog'},
		{'name' : 'juan', 'age' : 15, 'dialect' : 'pangalatok'}
	],
	'languages' : [
		{'name' : 'php', 'author' : 'rasmus lerdorf'},
		{'name' : 'python', 'author' : 'guido van rosum'},
		{'name' : 'ruby', 'author' : 'yukihiro matsumoto'}
	]
};

	var html = Mustache.to_html($('#languages').html(), ind);
	$('#container').html(html);
</script>
<div id="container"></div>

Here’s the code for the template. For our data there are some repeated items namely the name, dialect, and the author. All we have to do is to place those repeated items inside of the section. If you remember when looping through an array we placed a period {{.}} this time we place the actual name of the item inside the section.

<script id="languages" type="text/html">

<h1>People</h1>

<ul>
	{{#people}}
	<li>
	Name: {{name}} 
	Age: {{age}}
	</li>
	{{/people}}</ul>
	
<hr/>
<h1>Languages</h1>

<ul>
	{{#languages}}
	<li>
	Name: {{name}} 
	Author: {{author}}
	</li>
	{{/languages}}
</ul>
</script>

There are also times when the data source is 3 or more properties deep such as this one:

<script type="text/javascript">
	var characters = {
		deep : {
			'DragonBall' : {
				'Characters' : ['goku', 'gohan', 'trunks', 'cell', 'vegeta'],
				'Techniques' : ['kame hame wave', 'instant transmission']
			},
			'Onepiece' : {
				'Characters' : ['luffy', 'ace', 'zoro', 'nami', 'usopp', 'sanji', 'franky', 'robin', 'brook'],
				'Techniques' : ['Diable Jambe', 'haki', 'hocho sabaki', 'fleur', 'asura']
			}
		}
	};

	var html = Mustache.to_html($('#characters').html(), characters);
	$('#container').html(html);
</script></pre>
<div id="container"></div>
<pre>

If that’s the case all you have to do is to use dot notation to access the properties that you want. Unfortunately bracket notation doesn’t seem to be working on Mustache so better stick with a naming convention that works with dot notation. Check out the JavaScript best practices from the JavaScript toolbox if you want to learn about names that works with dot notation. I’ve also linked to it in the resources section in case you’re far-sighted. Here’s how we access those properties from our template:

<script id="characters" type="text/html">

<h1>Onepiece Characters</h1>

<ul>
	{{#deep.Onepiece.Characters}}
	<li>{{.}}</li>
	{{/deep.Onepiece.Characters}}
</ul>

<h1>Onepiece Techniques</h1>
<ul>
	{{#deep.Onepiece.Techniques}}
	<li>{{.}}</li>
	{{/deep.Onepiece.Techniques}}
</ul>

</script>

Lastly I’m going to show you an example on how to use data from a remote source (let’s just pretend that its from a remote source) and use that data for our mustache templates. For this example were going to use PHP for the backend and some AJAX methods from jQuery (though it should be AJAJ- Asynchrounous JavaScript and JSON since were using JSON not XML, but yeah AJAX sounds nicer) to fetch the data from PHP.

First we’ll have to create a new PHP file (data.php) and then build the data using arrays. JavaScript flavored arrays to be exact. I’m using PHP 5.4 which is the latest version of PHP at the time of writing of this article. It’s always a good idea to use the latest version of a library, a framework or a programming language since there are lots of new features and benefits. More information about what’s new in PHP 5.4. Here are the contents of the php file that serves as our data source. As you can see were just using arrays and then convert it to JSON string using the json_encode() method in php. This is an important step since its easier to make use of JSON in JavaScript.

<?php $data = ['ninjas'=>[
			'naruto'=>['name'=>'naruto', 'skills'=>['rasengan', 'kage bunshin']],
			'sasuke'=>['name'=>'sasuke', 'skills'=>['chidori', 'sharingan']],
			'lee'=>['name'=>'lee', 'skills'=>['leaf hurricane', '5 gates']]
		]
		];

echo json_encode($data); //convert array to JSON string
?>

And we just fetch the data using the $.post method in jQuery. A quick and nice method for doing AJAX request in jQuery. It’s actually a convenience method for the $.ajax method to make life easier for our fingers that are tired from everyday coding.

<script type="text/javascript">
$.post('data.php', {}, function(data){
		var ninja = JSON.parse(data); //parse JSON string from PHP to convert it to an object
		var html = Mustache.to_html($('#ninja').html(), ninja);
		$('#content').html(html);
	});
</script>

<div id="content"></div>

And for the template we use the dot notation again to access the skills of each ninja. Remember to start with the root property which is ninjas:

<script id="ninja" type="text/html">
<h1>Naruto</h1>
<ul>
	{{#ninjas.naruto.skills}}
	<li>{{.}}</li>
	{{/ninjas.naruto.skills}}
</ul>

<h1>Sasuke</h1>

<ul>
	{{#ninjas.sasuke.skills}}
	<li>{{.}}</li>
	{{/ninjas.sasuke.skills}}
</ul>

<h1>Rock Lee</h1>

<ul>
	{{#ninjas.lee.skills}}
	<li>{{.}}</li>
	{{/ninjas.lee.skills}}
</ul>

</script>

Conclusion

So yeah I guess that’s it for this tutorial on how to use Mustache for templating. You’ve learned the basics of Mustache, how to access properties using the dot notation, using JSON data as a data source for your templates. I hope you learned something and please share this tutorial if you like it.

Resources

Useful sites for freelancers looking for online jobs

Whether you’re a currently unemployed professional looking for online jobs or an employee of a certain company looking for things to do on your free time here are some useful sites that will help you find online jobs.

 

WorkFu

A new startup that lets you find jobs both local and telecommute. If you believe you’re pretty competent in your field then this is the site to be. Because you will mostly find jobs at the expert level here. Really useful if you have lots of superpowers.

image

 

Staff

A unique site where you can find jobs that fits the skill that you have included in your profile. It’s unique in the sense that you’re not the one that’s going to look for jobs it’s the site that’s going to send jobs that you might be interested in applying for based on your skills. For example you have included JavaScript, PHP, MySQL as your skill. You will receive emails and text messages (if you have included your cellphone number) on jobs that matches your skills. I believe this is really pretty awesome.

image

 

oDesk

A pretty old one but still useful. Here you get to propose for the price that you want if you think their budget is too low. You can also upload your resume and compose your cover letter or application letter. A really pretty normal jobs site but since it was founded in the year 2003 its already given that it has the most job postings so its  pretty populated with jobs which makes it a bit hard to find the jobs that you’re really interested in.

image

 

LinkedIn

The number one professional networking site where you get to connect with professionals in your field. But it doesn’t end there because you can actually join groups like CodeIgniter developer group, web developer/ web design groups. And you can find relevant job posting on the group. For example if you joined a web developer group you will only find job postings that are related to web development (html, css, javascript, etc.)image

 

Craigslist

You might have heard of this site already but not aware that you can actually post and look for jobs. There’s always a new job posting everyday and if you’re lucky most of them are also online or telecommute jobs. What’s good about this site is that you won’t see how many people applied for the job that you’re trying to apply for. In my opinion this is very useful and it will make you feel like you’re the only person applying for the job which gives you the confidence that you have better chance.

image

 

Freelancer

You might already know this one since it comes close to the word Freelance. Really useful if you already belong to a company because this site is mostly populated by companies looking for online jobs. So if you’re an individual freelancer you might only have luck if you’re really awesome and possess superpowers. One useful feature of this site is the email notifications on the jobs or projects that matches your skills.

image

 

Elance

Similar to freelancer.com because you also have to write proposals which is much like an application letter. Jobs can either be fixed rate or per hour. But before you can look for jobs you have to pass an online test which is really easy since its an open book test. After that you can take something like a certification exam to prove that you’re actually competent in the skills that you included in your profile. This is optional but you get better chances of getting hired for the job if you pass these exams.

image

 

GetACoder

As the name of the site suggests this is a site specifically dedicated to coding. You will most likely find jobs like website design, website development, usability testing, and search engine optimization. Most of the jobs here are project-based.

image

 

ScriptLance

A site where you can find jobs on programming, design, writing and marketing. Most of the jobs here are per project.

image

 

That’s the end of this list. If you know of other useful sites for finding online jobs then talk to me in the comments. Thanks!

How to convert documents into pdf using PDFCreator and PHP

Introduction

In this tutorial I’m going to show you how you can convert document files such as word (doc, docx), powerpoint (ppt, pptx), excel (xls, xlsx) and image files into pdf format using pdfcreator.
Pdfcreator is a free software used to create pdf files from different file types.
You may want to use it to convert the files which are uploaded into your website into a single format.

Configure PDF Creator

After downloading and installing pdfCreator you may want to have the files auto-save into a default location so that there will be no user intervention that will be needed when converting files into pdf. To do that open up pdfCreator, press ctrl + O in your keyboard to launch the options. Under the Program Menu you will see the auto-save option. Check the use auto-save checkbox and select PDF as the auto-save format. For the filename I used the original title of the file plus the date and time in which it was converted so as to avoid duplicate filenames. Finally select the directory in which you want to save the pdf file that will be generated. It has also a send email feature but we won’t be delving into that in this article.

image

Batch File

Create a batch file which will be used to call pdfCreator to do its job. A batch file has an extension of .bat so be sure to save the text file with this extension so that it will be executable. The batch file will contain the call for pdfcreator.exe and then the parameters (command plus the location of the file that you want to convert)

pdfcreator.exe /PF"D:\files\asset_flow.xlsx"

Next we need to create another batch file that will clear the contents of the batch file that we created above. This is to prevent the files from being converted more than once. Note that this must only be executed at a time wherein you’re certain that files has all been converted.

@echo on > launcher.bat

If your application is running 24/7 then you might want to think of another solution as this might not be possible if there’s no idle time for your application.

Upload Script

I assume that you already have an upload script which will upload the files in a certain location so I won’t delve into that. What were gonna do here is to add code into your upload script that will put contents into the batch file that we created earlier.

<?php
$filename = $_POST['filename'];

//file location + filename
$command = "pdfcreator.exe /PF";
$contents = file_get_contents('launcher.bat');
file_put_contents('launcher', $contents . "\n" . $command . $filename);

What the code above does is to append the command, filename and file location to the current contents of the batch file.

Task Scheduler

Finally you have to decide which time you’re going to execute the batch file that mass converts the files that were uploaded and the batch file that clears the contents of the first batch file. You can do this using the task scheduler on Windows or setup a cron job if its on Linux.

Conclusion

PDFCreator is a quick and easy way to create PDF Files from other document files such as Word, Powerpoint and Excel. If you ever need the functionality to convert documents to PDF Files automatically then use PDFCreator.