Playing with Models in Backbone.js

Yeah finally I got my hands dirty on Backbone.js and this time I’m also going to share to you what I’ve learned about backbone.js models.

Models in backbone.js is pretty much like the models in the MVC in server-side scripting language like PHP. If you aren’t familiar with the Models in the server-side they’re used for representing the data in the database. It’s a place where queries are being written. In simple terms data manipulation and retrieval happens in the Model.

But here were talking about the Models in the client-side particularly the Models used in Backbone.js. As I have said earlier they’re pretty much the same with the Models you used in the server-side in the sense that they also represent or store data temporarily.

If you want to learn the basics of Backbone.js before digging into this tutorial scroll all the way to the bottom and you will find some of the Backbone.js resources that I recommend.

 

Requirements

  • jQuery – for dom manipulation and event delegation
  • Underscore.js – hard dependency of Backbone.js
  • Backbone.js – gives structure to JavaScript applications

 

Output

What we will be working on today is a very simple application that allows us to add people on a table. Feel free to put on some css if you want because this really looks very ugly without the styling.

image

Of course I’m only going to teach you how to use Models in Backbone.js in this tutorial as you might not know I’m also learning Backbone.js as I write this tutorial so this very simple application is going to evolve in simply making use of Models to using all the basic components of Backbone.js like the Views, Collections, and Routers at the end of this series of tutorials were also going to connect our application to Couch DB a NoSQL Database which uses JSON to store data.

 

Include

First you need to include the scripts that we need on the head portion.

<script src="jquery171.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>

Note that jQuery isn’t actually required if you have other means of manipulating the DOM, another library that you might be using then use it instead of jQuery.

 

Markup

Next is the markup where we are going to input the name and the age of the person:

<p>
<label for="name">Name:</label>
<input type="text" id="name"/>
</p>

<p>
<label for="age">Age:</label>
<input type="text" id="age"/>
</p>

<p>
<input type="button" id="btn_save" value="save"/>
</p>

Then the container for the table:

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

 

Model

Were not ready to create a new Model which we are going to temporarily store the name and age of the person.

<script>
var people = Backbone.Model.extend({

});
</script>

Inside the people Model is the constructor, this isn’t required but we need to be able to see something when a new people object is created. This is also the best place to put listeners. As the name suggests the listeners are simply used to monitor the value of a certain data in the model.

initialize: function(){

}

Inside the constructor you need to bind the error event. This simply listens to the

this.bind('error');

Next is the defaults or the default attributes and values that you want to add on your Model. These are simply the fields in a table when were comparing it to a database.

defaults:{
	names 	: [], //stores all the names
	ages	: [], //stores all the ages
	name 	: '', //will store the current value of name
	age	: '' //will store the current value of age
}

Next is the validate method. As the name suggests this method is where we put the validation logic for our model. This is where we check for required fields, number-only fields, email addresses, etc. If the idea doesn’t excite you then you might as well use happy.js, html5validate or the jQuery Validation plugin.

In the example below we simply check whether the attributes name and age have values on it and return an error if either of them doesn’t have a value. Remember that when you return a value from the validate method it should always be the error that you’re returning. In other words this is not the place where you check for things that have passed the validation.

validate : function(attributes){
	if(attributes.name == '' || attributes.age == ''){
		return attributes.name + " "  + attributes.age;
	}
}

Lastly instantiate the people model.

var p = new people();

 

Saving

Next is the code for saving values into the people model. Begin with delegating the click event into the save button.

$('#btn_save').click(function(){

});

Inside the event get the name and age inputted by the user.

var name 	= $.trim($('#name').val());
var age  = $.trim($('#age').val());

Also get the current names and ages that are on the people model.

var cur_names 	= p.get('names'); //array of names
var cur_ages	= p.get('ages'); //array of ages

Then simply set the name and the age. This saves the value of name and age inputted by the user into the name and age attributes in the people model.

var check = p.set({'name': name, 'age': age});

The set method returns a value of false if the value is not saved into the attribute that you have specified and it returns an object when its successfully saved on the attribute that you’re referring to:

image

If check is a truthy value then the code inside of it will be executed if not then issue an alert to the user that all fields are required. I recommend that you read this article by James Padolsey on truthy and falsey values if you don’t have an idea on what truthy and falsey values are.

if(check){ }else{

alert(‘all fields are required!’);

$('#name, #age').val('');

}

If both the name and the age is inputted by the user we perform the following code.

First push the name and age inputted by the user into the current names and ages. Push() is a built-in method in JavaScript that allows us to push a single item at the end of the array.

cur_names.push(name);
cur_ages.push(age);

Set the value of the names attribute to be equal to the current names. Do the same with the ages attribute.

p.set('names', cur_names);
p.set('ages', cur_ages);

Of course you can also do it this way if you’re in a hurry:

p.set({'names' : cur_names, 'ages' : cur_ages});

Lastly, clear the textboxes:

$('#name, #age').val('');

 

Table

Next we build the table where were going to append the names and ages of the people that were adding.

First select the body.

var body = document.getElementsByTagName('body')[0];

//select the body tag

You can easily do this in jQuery through something like this:

var body = $('body');

But I’m currently practicing my plain js skills so please bear with me if you see some good old JavaScript in the examples.

Check if the there is no table in the page yet.

if($('table').length == 0){ //create the table }else{

//get the tbody

}

Inside it we create the table headers and table body. (If you have keen eyes you might have noticed that I’ve pretty much forgotten about the thead but it’s not actually required so we’ll be fine)

var tbl = document.createElement('table'); tbl.setAttribute('border' , '1'); //set borders to 1 var tr = document.createElement('tr'); //table row for headers var th_1 = document.createElement('th'); //header for names var th_2 = document.createElement('th'); //header for ages th_1.innerHTML = 'Name'; //header text for header names th_2.innerHTML = 'Age'; //header text for header ages

//append the headers into the table row

tr.appendChild(th_1); tr.appendChild(th_2);

tbl.appendChild(tr); //append the table row into the table var tbody = document.createElement('tbody'); //tbody

If the table is already created we simply select the table and the tbody:

}else{
	var tbl =document.getElementsByTagName('table')[0];
	var tbody= document.getElementsByTagName('tbody')[0];
}

And here’s the code that’s we will be executing everytime a new valid person(with both name and age) is created by the user.

var tr_2 = document.createElement('tr'); //create new table row

var td_1 = document.createElement('td'); //create table definition var td_2 = document.createElement('td'); //set table definition text td_1.innerHTML = name; td_2.innerHTML = age;

//append the table definition into the table row

 

tr_2.appendChild(td_1); tr_2.appendChild(td_2); tbody.appendChild(tr_2); //append the table row into the tbody tbl.appendChild(tbody); //append the tbody into the table body.appendChild(tbl);

 

Conclusion

Yeah! I guess that’ pretty much all we have to talk about. Be sure to check out the resources I mentioned below if you want to learn more about Backbone.js since I won’t be mentioning it again on the next parts of this series. In this tutorial we’ve created a very simple application using underscore.js, backbone.js and jQuery. As I have said earlier were going to make this application more awesome as we go through the series.

 

Resources

Playing with Underscore.js

In this tutorial I’m going to introduce to you a JavaScript Library called Underscore.js. It’s a library used to make your life easier as a Javascript developer. It has a bunch of different functions used for grouping, sorting, and mapping objects.

I’m learning underscore.js as I’m writing this so if you don’t understand something just Google it and enlightenment will be yours.

I recommend that you play with underscore.js on the console, it’s the best place to introduce yourself to a JavaScript library since you will immediately see the output of what you’re writing.

 

Difference

This returns the items in an array which exists on the first argument but does not exist on the second argument. Which means that its return value depends upon the order of the arguments.

var ar1 = [1, 2, 3, 4, 5, 6];
var ar2 = [2, 3, 7, 9, 10, 1];

_.difference(ar1, ar2); //returns [7, 9, 10]

This can also work with arrays composed of strings:

var amp1 = {'names' : ['wern', 'paul', 'falk']};
var amp2 = {'names' : ['w', 'fa', 'wern']};

_.difference(amp2.names, amp1.names); //returns ["w", "fa"]

 

Uniq

The uniq method removes all the duplicates in an object. I don’t know how many arguments it could take but I managed to get two in the example below:

var names1 = ['paul', 'joseph', 'mark', 'matthew']; var names2 = ['joshua', 'ahab', 'michael', 'mark', 'paul']; _.uniq(names1, names2); //returns: ["paul", "joseph",

"mark", "matthew"]

 

All

This is one of my favorites. What his does is to check if all the items in an object meets the criteria that you specify. In the example below we are checking if all the items in the array ar1 is a number:

var ar1 = [1, 2, 3, 4, 5, 6]; _.all(ar1, function(value){ return typeof value == 'number'; });

//returns true

However if we try to put a string and a boolean:

var ar1 = [1, 2, 3, 'im a string', 4, 5, true, 6];

_.all(ar1, function(value){ return typeof value == 'number'; });     //returns false

One possible use case for this method is input validations.

 

Map

I’m not particularly where can I use this one but it looks pretty cool. What this does is to map values to the items in the object that you specify.

var ar1 = [1, 2, 3, 'im a string', 4, 5, true, 6];

_.map(ar1, function(val){ return val + " awesome"; })

And so the output depends on what you specified in the function body. The code above appends the word awesome to every item in the object ar1.

 

Select

This works just like the select query in SQL if ever you have worked with databases before. This requires 2 arguments the first one is the object that you want to use as your data source and the second argument is the function which is equivalent to the actual query in SQL. What I did below is to select all the items in the array ar2 that is greater than 1.

var ar2 = [2, 3, 7, 9, 10, 1]; _.select(ar2, function(val){ return val > 1; })

//returns [2, 3, 7, 9, 10]

 

SortBy

This allows you to sort the items in your object any way you want. In the example below I sorted the array ar2 randomly.

var ar2 = [2, 3, 7, 9, 10, 1]; _.sortBy(ar2, function(val){ return Math.random(val); });

//returns items in ar2 in a random order

 

Rest

Returns all items in the object except the first one.

var x = [1,2,3,4];

_.rest(x); //returns [2, 3, 4] 

 

Initial

Returns all items in the  object except the last one.

var x = [1,2,3,4];

_.initial(x); //returns [1, 2, 3]

 

Find

Returns the first item in the object that matches the criteria that you specified.

var x = [1,2,3,4];

_.find(x, function(v){ return v > 3; }); //returns 4

 

Filter

Similar to select, I don’t really know the difference.

var x = [1,2,3,4];

_.filter(x, function(v){ return v > 2;}); //returns [3, 4]

 

Pluck

Plucks out the values associated with the key that you specify.

var anime = [{title: 'death note', main_char: 'light yagami'},   {title: 'pokemon', main_char : 'ash'}, {title: 'd-grayman' , main_char : 'allen walker'}]; _.pluck(anime, 'main_char');

//returns [light yagami, ash, allen walker]

 

Shuffle

Returns the items in an object in a random order.

var x = [1, 2, 3, 4];
_.shuffle(x);

 

Union

As the name suggests, this merges all the items in the objects that you specify as the argument. Duplicates are removed in the process which means that only unique items are returned by the method.

var x = [1, 2, 3, 4];
var y = [4, 88 , 9, 20];
var z = [5, 5, 7, 22, 1, 2];

_.union(x, y, z);  //returns [1, 2, 3, 4, 88, 9, 20, 5, 7, 22]

 

Intersection

Returns all the items which exists on all of the objects that you specify.

var x = [1, 2, 3, 4];
var y = [4, 88, 2, 1, 9, 20];
var z = [5, 5, 7, 22, 1, 2];

_.intersection(x, y, z); //returns [1, 2]

 

Range

Returns an array of numbers that are within the range that you specify. The usage of the arguments depends on the number of arguments that you specify. If you only specify a single argument it is assumed that the initial value will be 0 and the step will be 1. Remember that the array that is returned is always zero-indexed.

_.range(4); //returns [0, 1, 2, 3]

If you specified 2 arguments then it is assumed that the step is 1 and the first argument is the initial value and the second argument is the terminal value.

_.range(2, 10); //returns [2, 3, 4, 5, 6, 7, 8, 9]

If you specified 3 arguments the first argument is the initial value, the second argument is the terminal value, and the third argument is the step. You can make use of this to easily create a multiplication table of any number.

_.range(2, 20, 2); //returns [2, 4, 6, 8, 10, 12, 14, 16, 18]

 

bindAll

Binds functions into specific events in an object(elements). It’s like event-delegation in jQuery.

Since were doing things in the console and in an empty page, we first need to create the elements that we will be working on.

var spark = document.createElement('input'); //creates an input element
spark.setAttribute('type', 'button'); //set type to button
spark.setAttribute('value', 'spark'); //set value to spark
spark.setAttribute('id', 'spark'); //set id to spark

var body = document.getElementsByTagName('body')[0]; //select the html body tag
body.appendChild(spark); //inject the button into the dom

After creating the element and injecting it into the DOM we set the properties.

var spark_props = {
   name : 'spark boom',
   onClick : function(){ alert('name is:  ' + this.name); }
}

Remember that you can add any property any time you want.

spark_props.boom = 'kapow'

Or even modify existing ones.

spark_props.name = 'bam!!!'

Call the bindAll() method to bind all the properties together.

_.bindAll(spark_props);

Finally, bind the click event to the button using the onEvent method as its action.

$('#spark').bind('click', spark_props.onClick)

 

Once

Creates a clone of the function which can only be called once. One use case that I could think of is when submitting forms sometimes users tend to click on the Submit button multiple times.

var save = _.once(function_to_send_data_to_server);

 

Each

Pretty much like the .each() method in jQuery if you’ve ever used jQuery before. It is used to iterate through the items of the object that you specify.

_.each(['re','mi','fa'], function(va){
   console.log(va);
});
//outputs:
re
mi
fa

 

Functions

Returns an array of functions stored in the object that you specified. The example below returns all the functions associated with Backbone.js, the number of functions returned only shows how lightweight it is.

_.functions(Backbone); returns

["Collection", "History", "Model", "Router",

"View", "noConflict", "setDomLibrary", "sync", "wrapError"]

 

Times

Takes up two arguments the first one is the number of times you want to execute the given function which is the second argument. You can pretty much use this like the _.each method.

var anime = [{title: 'death note', main_char: 'light yagami'},  

{title: 'pokemon', main_char : 'ash'},

{title: 'd-grayman' , main_char : 'allen walker'}];

 

_.times(anime.length,

function(index){console.log(anime[index]['main_char']);})

 

//outputs:

light yagami

ash

allen walker

 

Result

Reminds me of the getters and setters _.result is pretty much like the getter method in every programming language but this time you can either get the value for a particular key or execute a particular function.

 

Conclusion

That’s it! You’ve learned how to use some of the useful methods in underscore.js that you can use in your projects. If you’re already using jQuery you can use underscore.js as an enhancement since they will work together just fine.

 

Resources

How to create a raffle program

In this tutorial I’m going to show you how to create a raffle program which will randomly select records from a mysql database.

 

Requirements

  • jQuery
  • Wampserver

 

Initial Script

First, create a new file and call it raffle.php. This is where we will put the codes for randomly selecting records using javascript.
Declare an array which will temporarily store the names of the participants and winners. Then initialize the winner_index to 0. If you have already spent some time in programming, you know that winner_index is a way to keep track how many winners were already selected on the current session. This is also a way of making sure that we store each of the winners on a different index in the array.

var participants = [];
var winners = [];
var winner_index = 0;

Once the document has been fully loaded, we initialize the total number of names to be displayed to 30. Then we create an event handler once btn_random is clicked by the user. We haven’t created the btn_random yet since where still on the script so hold your horses and keep reading.
Clicking the btn_random button will cause a post request to the server and this is through the $.post() function in jQuery. It’s a convenience function primarily used to post or load data from the server. In this case, were loading the data from loader.php a script which we will create later. But what it does is select random records from the database and then returns a JSON string which is then used by our raffle program. As you can see in the code, we used $.parseJSON() function before assigning the data to the array of participants. This is used to convert the JSON String into a Javascript Object. This is to prevent the data from being treated as a string. Finally, we execute the RunRaffle() function which takes up 2 arguments: the total number of names to raffle and then the array of names to raffle.

$(function(){
	var total_count = 30;	
	$('#btn_random').click(function(){
		$.post('loader.php', function(data){
		participants = $.parseJSON(data);
			
		RunRaffle(total_count, participants);
	                 });
	});				
});

 

Loading the data

I guess its only proper to first show you how to load the names that were going to raffle from the database before I go through the meat of the program.

Create a new file and name it loader.php. Include your database configuration. Then set the character set to UTF8, this makes sure that we don’t get any errors when dealing with names which are made up of characters which are not very friendly when you retrieve them from the database.
Nex, we select the records randomly from the database and that is by using the RAND() function in mysql. If you’re interested with the technicalities just visit the link. But basically the RAND() function is used to randomize the results which are being returned from a query but its only effective if there are a hundred records or more. Its almost always certain that this function will select the same records over and over again but only in a different order. If say you only have 30-100 records. And note that RAND() function is actually a very expensive operation when it comes to performance so don’t use it on production. But its perfectly fine if you use it on just raffle programs or similar operations.

<?php

require_once('seminar_config.php'); $db->query("SET CHARACTER SET utf8"); $select_random = $db->get_results("SELECT participant FROM tbl_participants

WHERE state = 1 OR state = 4 ORDER BY RAND() LIMIT 30");

 

?>

We then loop through the records and assign it to an array. As you can see we don’t actually need to assign an index to the current record since php does this automatically for us, that’s just sweet! After were done looping through all the records we just use the json_encode() function to convert the $data array into its JSON String representation. There’s also a note from the php.net site that this function only works for UTF8 encoded data so setting the character set to UTF8 in mysql is  actually really useful. Yes you can try not setting the character set to UTF8 and the function will still work, but not for all characters. If json_encode() doesn’t understand it, it will probably be set to null and you’ll get some null values on your JSON string.

if(!empty($select_random)){
	foreach($select_random as $k=>$v){
		if($v->participant != null){
			$data[] = $v->participant;
		}
	}
	echo json_encode($data);
}

 

Meat

After loading up the data that we need its now time to do the code for the presentation of the raffle. The visual signal that will let the audience know that this is actually a raffle program. Because you can’t just pull out random names from the database without any visual impact. And were using jQuery for that purpose, all we have to do is to present a specified number of names. In this case we want 30 names to show up on the interface, then we just change the background color of its container in a successive fashion. There are 3 elements which makes this program tick:

  • Math.random() – although we already randomize what were selecting from the database, we also do this on the client side for presentation purposes.
  • .next() – jQuery’s .next() function which is basically used to determine the next element after the current element that is being selected.
  • setTimeout() – a Javascript function which is used for delaying the execution of another function. In the raffle program it is used to achieve the effect of slowly decreasing the speed in which the light is looping through the names while time passes by.

Declare the RunRaffle() function:

function RunRaffle(intCount, people){
   //magic happens here
}

Inside it we first initialize where we are going to append the list of names. In this case were appending it into an element which has the id of raffle. This element is an ordered list. After that, we just empty the current contents of the ordered list. This is to make sure that we don’t populate the whole interface with a bunch of names from the database.  Don’t worry we’ll also be writing all the html later.

var jRaffle = $("#raffle");
jRaffle.empty(); //this clears all the contents of the ordered list

Next, we just fill the ordered list with the names that we have fetched earlier from the database. But before we actually append it into the list we first check whether its null and that its not an existing winner. This is some sort of an assurance that we don’t put the names of the winners on the list of names to raffle in case the query failed us.

for (var intI = 0 ; intI <= intCount ; intI++){
			
if(people[intI] != null && check_existing(winners, people[intI]) == false){
	jRaffle.append("<li><div class='grey'>" + people[intI] + "</div></li>");
}
}

Next, we change the background color of the first name in our list.  Then Initialize the pause time, the pause time is the amount of time that we are going to run the program. Finally, the intDelay is the amount of time used to jump from one name to another.

var jCurrentLI = jRaffle.find("li:first").addClass("on");  //find the first name that was appended on our list
var intPause = 40; //set initial value of pause time
var intDelay = (4500 + (Math.random() * 2000)); //get time to wait before chaining pause time

Next, create an anonymous function and assign it to a variable called Ticker.

var Ticker = function(){

}

Inside it we define the next name to be selected, if we don’t have anything else on the list we go back to the first name on our list.

var jNextLI = jCurrentLI.next("li"); //next name to highlight
if (!jNextLI.length){ //check whether jNextLI has something in it     jNextLI = jRaffle.find("li:first"); //go back to the first name
}

Then we remove the highlight from the current name and add the highlight to the next name.

jCurrentLI.removeClass("on"); //remove highlight from current
jjNextLI.addClass("on"); //add highlight to next

Then check  whether to make the chaining slower. Remember that the higher the number of the variable intPause, the slower the movement from the current name to the next name will execute. This means that the intPause variable effectively determines the next winner after we reach a certain value.

jCurrentLI = jNextLI; //for the next iteration
if (intDelay > 0){
	intDelay -= intPause; //intDelay = intDelay – intPause
} else {
	intPause *= (1 + (Math.random() * .1)); //intPause = intPause * random value
}

Finally, when the intPause variable reaches a value of 400 or above we stop the current session of iterations. What we do here is to append the current winner to the list of winners and that is if the current name isn’t already stored in the array of winners, for this we used the check_existing() function which we will create later. We also submitted the name of the current winner to winners.php which basically just saves the name of the current winner into our database and changes its state so that it won’t be selected again. If for some reason a name is selected twice, we just clear out the container which stores the name of the current winner and we don’t add anything to the list.

if (intPause >= 400){
	iif(check_existing(winners, jCurrentLI.text()) == false){
		$('#winners').append('<li>' + jCurrentLI.text() + '</li>'); //append current winner to list of winners
		winners[winner_index] = $.trim(jCurrentLI.text()); //housekeeping  $.post('winners.php', {'winner' : $.trim(jCurrentLI.text())}); //save winner to database
		$('#divider').html(jCurrentLI.text()); //current winner
		
		winner_index++; //add 1 to the index
					
	}else{
		$('#divider').html(''); //clear the container for current winner
	}
				
} else { //while intPause is not >=400 increase delay for Ticker
	setTimeout(Ticker, intPause); //set delay for the ticker to be called
}

Then we just call the anonymous function through the variable Ticker. Note that were calling it just like a normal function.

Ticker();

 

Check Existing

For the check_existing() function it returns true if it found the name of the current winner in the array and false if it didn’t find it. It takes up two arguments, the winners array and the selected name.

function check_existing(arr,obj){
	 return (arr.indexOf(obj) != -1);
}

 

Commit Selection

The last thing that we have to do is to commit the selected winners to our database. Just change the state of whoever gets selected into something that’s not specified on the select statement.

$winner = mysql_real_escape_string($_POST['winner']); 

$db->query("UPDATE tbl_participants SET state=4 WHERE participant='$winner'");
$db->query("INSERT INTO tbl_winners SET winner='$winner'");

Yup I know what I said above might be confusing so here’s an explanation. For example on your query for selecting records you only select those whose state is 1:

SELECT * FROM tbl_participants WHERE state=1 ORDER BY RAND();

All you have to do in your update is to set a different state:

UPDATE tbl_participants SET state=4 WHERE participant=’something’

Then finally insert the name of the winner into another table. That is if you want to keep track of those who are selected. But you can probably just select all records with the state of 4 if you don’t want to do this extra step.

 

Markup

I explicitly delayed the html for the last part since this is the most boring part.

<div id="header">
	<img src="images/raffle_header.png" />
</div>
<div id="container">
<input type="button" id="btn_random" value="Select"> <!-execution->
<ol id="raffle"> <!-for viewing the names to iterate from–>
	
</ol>
</div>

<div id="bottom">
<div id="current">

	<p>Current:</p>
		<div id="divider"> <!—for viewing the current ->
		
		</div>

</div>
<div id="list">

<p>Winners:</p>
	<div id="winners"> <!—for viewing the list of winners->

	</div>
</div>
</div>

 

Sources

http://www.bennadel.com/resources/presentations/jquery/raffle.htm

How to find unique items in a javascript array

In this quick tutorial I’m going to show you how you can find the unique items in a javascript array. To demonstrate what do I mean when I say unique here’s an example:

I have an array called items which contains a set of letters, some are repeated and some are not.

var items = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'f', 'g', 'a'];

And when I try to get the unique items I should get this:

["b", "c", "e", "f", "g"];

The fact that you’re still reading this means that this is the one that you’re looking for. There’s a lot of ways to do this but here’s the first solution that I came up with:

First, declare an array which will hold the unique items:

var nopairs = [];

Then a variable which will temporarily hold the item which has a pair. This is the current non-unique item in the array.

var haspair = ' ';

And then declare the variable which will hold the current count of the unique items. Initialize its value to zero.

var nopair_ctr = 0;

Next, sort the array using the .sort() method in javascript and then assign it to a variable called arranged.

var arranged = items.sort();

Next, use the jquery.each() method to loop through the sorted array:

$(arranged).each(function(index){
  
});

Inside the loop we checked if the current item is not equal to the next item. Since the array has already been sorted we are assured that the items with the same value are always beside each other. This means that if we do it like this, it will always return false if the current item is equal to the next item.
We also checked if current item is not equal to the current item in the haspair variable. The haspair variable contains the last non-unique item in the array.
If the condition is met, we then store the current item inside the nopairs array using the nopair_ctr as its index. Finally we increment the nopair_ctr by 1 so that we won’t be storing the unique items on the same index.

if(arranged[index] != arranged[index + 1] && arranged[index] != haspair){
	nopairs[nopair_ctr] = arranged[index];
	nopair_ctr++;
}

If the condition above is not met, then we just change the value of the haspair variable to the current item in the array:

else{
	haspair  = arranged[index];			
}	

Finally if you try to output the contents of the nopairs array, you will only see the unique items in the array.

console.log(nopairs);

Life could have been a lot more easier if jquery’s unique() method does it:

console.log(jQuery.unique(items.sort()).sort());

But no, it doesn’t do it since it just pops out the duplicated items in an array and comes up with the following output.

["a", "b", "c", "d", "e", "f", "g"]

 

Conclusion

That’s it for the first article for this new year. You have learned how to use jquery and javascript to sort an array using the .sort() method in javascript, you also learned how to use jQuery’s unique() method to remove duplicates in array, lastly you have learned how to find the unique items in a javascript array.

How to submit javascript arrays to php

In this tutorial I’m going to show you a little example on how to submit javascript arrays to a php script.

 

Requirements

  • jQuery

 

HTML

First we have to write the html where we are going to input the items that we will put in the arrays.

<table>
<thead>
	<tr>
		<th>Name</th>
		<th>Language</th>
	</tr>
</thead>
<tbody>
	<tr>
		<td><input type="text" class="name_class" name="name[]"/></td>
		<td><input type="text" class="lang_class" name="lang[]"/></td>
	</tr>
	<tr>
		<td><input type="text" class="name_class" name="name[]"/></td>
		<td><input type="text" class="lang_class" name="lang[]"/></td>
	</tr>
	<tr>
		<td><input type="text" class="name_class" name="name[]"/></td>
		<td><input type="text" class="lang_class" name="lang[]"/></td>
	</tr>
</tbody>
</table>

Then the submit button.

<p>
<input type="button" id="btn_submit" value="submit"/>
</p>

Lastly, the <div> where we are going to place the result later on.

<div id="result"></div>

 

Javascript

Next, write the 2 function that will loop through all the contents of the textboxes allotted for the names and the textboxes for the languages. To make things easier, use the jQuery .each() function. The .each() is a function which iterates through  certain elements. You can make use of this to loop through all the contents of the element that you specify. In this case we are looping through the contents of the name_class and lang_class.

function name_loop(){
	var names_array = [];
	$('.name_class').each(function(index){
		names_array[index] = $.trim($(this).val());
	});
	return names_array;
}
	
	
function lang_loop(){
	var language_array = [];
	$('.lang_class').each(function(index){
		language_array[index] = $.trim($(this).val());
	});
	return language_array;
}

Note that you can only specify a single element on a .each() function. That’s the reason why we built 2 functions which basically does the same thing.

Next we need to specify what will happen when the user clicks on the submit button. Were just going to call the 2 functions that we wrote earlier then assign each of them to their own variables. And then we used the jQuery .load() function to call the php script where we are going to pass the arrays and at the same time loads the output from the php script back to the element that we specified, in this case the div with the id of result.

$('#btn_submit').click(function(){
	var names = name_loop(); //stores the array of names
	var languages = lang_loop();  //stores the array of languages
		
	$('#result').load('page.php', {'names' : names, 'languages' : languages}); //submit to php script
	$('input[type=text]').val(''); //empty all textbox
});

Lastly, create another file called page.php. This is the script where you are submitting the javascript arrays. And since we have passed in arrays, we’ll need a loop to actually iterate through all the contents of the array. For this purpose foreach loop is perfect. It’s the same with the jQuery.each() function. But this time were not iterating through element contents, were iterating through the contents of the array.

<table border="1">
<thead>
	<tr>
		<th>Name</th>
		<th>Language</th>
	</tr>
</thead>
<tbody>
	<?php foreach($_POST['names'] as $k=>$v){ ?>
	<tr>
		<td><?php echo $v; ?></td>
		<td><?php echo $_POST['languages'][$k]; ?></td>
	</tr>
	<?php } ?>
</tbody>
</table>

 

Conclusion

That’s it! You’ve learned how to pass javascript arrays into php using AJAX. You also learned how to use the jQuery’s .each() and .load() functions.

How to create a simple jquery image rotator

In this tutorial I’m going to show you how to create a simple jquery image rotator. Yes, there are quite a lot of image rotators that exists out there if you try and Google it. Those image rotators are either using html5 or jQuery for the effects that you see when the rotator moves from one image to another. But this time I’m going to show you the most basic way of creating an image rotator by using php and jquery.

 

Requirements

  • jQuery
  • Wampserver
  • A couple of images

 

Image array

At the top portion of your page, be sure to include the jQuery file.

<script src="jq.js"></script>

Next, specify a directory to be scanned. You may want to create a specified folder only for images:

$dir  = 'images';

Here’s what my directory looks like, just to give you an idea on how you should arrange the files:

image

Next, use the scandir() function in php. It requires a string argument which specifies the directory that you want to be scanned, in this case we want the images folder to be scanned for the image files that are inside it. The scandir() function returns an array of the list of files in the directory which you specified as an argument.

$images = scandir($dir);

Next, declare another array called $true_images. This is where we will store the real array of image file names. Because the $images array stores non-image values. Try using print_r($images) so that you’ll see what I mean.

$true_images = array();

Then do a foreach loop, to loop through all the items in the $images array. This time we use a function called is_file() which requires a string argument that stores the directory together with the image file name. This effectively removes the non-file values in the $image array and assign it into the $true_images array. Note that we didn’t specify any keys during the assignment of array items. Its because php does this automatically.

foreach($images as $k=>$v){
	if(is_file('images/'.$v)){
		$true_images[] = $v;
	}
}

 

Image Rotator

Next is the image rotator script.  Go ahead and type those <script> tags. Also specify that we only want to execute the script once the page is fully loaded in the browser.

<script>
$(function(){ //scripts inside this are only executed after page has been fully loaded

});
</script>

Next, assign the $true_images array into a javascript array. We used the php implode() function. To convert the $true_images array into a string separated with commas. So that it can be treated as a javascript array.

var image_array = ["<?php echo implode('","', $true_images); ?>"];

Declare the index and last_index. The index is the value that we are going to increment, it’s the key to changing the images. Were basically going to reset it when it reaches the last_index. Which means that this image rotator is not going to be displaying random images. Its only going to display the first image in the array up to the last and then go back again.

var index = 0;
var last_index = image_array.length;

Next, build a javascript function called image_rotator(). What it does is to change the source attribute of the image tag with the id of imgcontainer. It changes the image displayed by making use of the index. The index will be incremented by 1 every time the image_rotator() function is called. And reset back its value to 0 once the last_index has been reached.

function image_rotator(){
			
	$('#imgcontainer').attr('src', 'images/' + image_array[index]);
		index = index + 1;
				
		if(index == last_index){
		index = 0;
		}
}

To make all of this work out, you need to call the image_rotator() function and use the setInterval() to execute it every 2500ms or whatever interval you would like to specify.

setInterval(image_rotator, 2500);

And here’s the html that is manipulated by our image rotator.

<div id="images">
	<img src="images/1.jpg" id="imgcontainer" width="400px" height="500"/>
</div>

 

Conclusion

Okay, that’s it for this tutorial. You’ve learned how to create a simple image rotator using jQuery and php. You also learned a couple of php functions which you can use to scan for files in a specific directory. Thanks for reading!

How to create a chat box using jquery and php

Yo! what’s up? It’s been 2  weeks since my last post so I ‘m going to try to make up for those 2 weeks that I haven’t posted anything on my blog.

In this tutorial I’m going to show you how to build a simple chat box using jQuery and php.

 

Requirements

 

Resources

I guess this is a new portion so let me introduce to you what resources is. Resources is where you can find the links to some of the sites that in one way or another has given me an idea on how to build something. In this case a chat box.

 

Procedure

First thing that you have to do is to create your working folder where you will put all the files for this mini-project.

Next, create the database where we are going to store the user information and messages.

Here’s the table structure for users:

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

And the table structure for the chat box:

CREATE TABLE IF NOT EXISTS `chat_box` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sender` varchar(30) NOT NULL,
  `sendto` varchar(30) NOT NULL,
  `message` varchar(140) NOT NULL,
  `date_sent` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=33 ;

You can use the table structures above. But you can also build your own if you want. Since what I’m showing you is very minimal. You might want to add up some fields and other tables as well.
You might also want to insert some data on the table for users using phpmyadmin or any database manager that you know. Since were not going to create a page where the users can register.

 

Next, create a page where the users can login.

<?php require_once('tutorials_config.php'); //database configuration file ?>

<!-—form—-> <form action="login.php" method="post"> <p> <label for="username">Username:</label> <input type="text" name="username" id="username"> <input type="submit" value="login"> </p> </form> <?php

//form processing if(!empty($_POST)){ $username = clean($_POST['username']); $exist = $db->query("SELECT username FROM users WHERE username='$username'"); if($exist == 1){ header('Location:test.php'); //redirect to chatbox page $_SESSION['user_logs'] = $username; //create a session for user }else{ header('Location:login.php'); //redirect to login page } } ?> <?php

//sanitize user input function clean($str){ return trim(mysql_real_escape_string($str)); } ?>

First, you have to include your database configuration file at the uppermost portion of your php file. Then create an html form. You might have notice that I only have a text field for the user id. You can also modify the code and add a password if you want. But as I have said earlier, I want to keep things as minimal and simple as possible. Please read the comments in the code to help you understand what it does.

If we have a login, we also need to have a logout.

<?php
session_destroy(); //destroy the session created from login page
header('Location:login.php'); //redirect to login page
?>

Again, this code is very minimal. It actually destroys the whole session. So if one person logs out, all the other people who is currently logged in will also be logged out. You can always improve this one if you like. That is by looping through all the users in the session and unsetting only the session for the user who wants to logout.

 

We’ve arrived at the point of interest. The chat box itself.
First, include the database configuration file. And check if a user session is already set:

<?php

require_once('tutorials_config.php');


if(empty($_SESSION['user_logs'])){ //check if user session is set
    header('Location:login.php'); //redirect to login page if user session is not set
}

?>

Next, include the files that you have downloaded earlier from the links in the requirements portion. The jquery file, jquery ui files, and the jquery chat box plugin files.

<link rel="stylesheet" href="ui-lightness.css" type="text/css" media="screen" />
<script type="text/javascript" src="jq.js"></script>
<script type="text/javascript" src="jq_ui.js"></script>    
<link type="text/css" href="jquery.ui.chatbox.css" rel="stylesheet" />
<script type="text/javascript" src="jquery.ui.chatbox.js"></script>

After that, create the html form for the chat box.

First, the link to the logout page. And the hidden field where we are going to store the username. I always use hidden fields when I want to store php generated values which I want to access through javascript later on. I don’t know what tricks you are using to achieve the same thing. But that’s the one that I’m using.

<p>
<a href="logout.php">Logout <?php echo $_SESSION['user_logs']; ?></a>
</p>
<input type="hidden" id="username" value="<?php echo $_SESSION['user_logs']; ?>">

Next, also create a text field where the user can choose whom to send the message. I used an auto-suggest field to fetch the usernames from the database except the username of the user who is currently logged in. I have previously written an article discussing about datalist you can check it out if you don’t know how to use datalist yet. I also mentioned there that datalist doesn’t work for Chrome yet, and I have no idea when will they have it on Chrome. So use Firefox 5 or higher if you want to make this work. On the other hand, you can use jquery ui auto-suggest so that you can make it work on all browsers.

Also create a button which will call up the chat box.

<p>
	<label for="chatwith">Chat with:</label>
	<input type="text" name="chatwith" id="chatwith" list="otherusers">
	<datalist id="otherusers">
	<?php 
	$current_user = $_SESSION['user_logs'];
	$users = $db->get_results("SELECT username FROM users WHERE username != '$current_user'");	
	if(!empty($users)){
	?>
		<?php foreach($users as $v){ ?>
			<option value="<?php echo $v->username; ?>"><?php echo $v->username; ?></option>
		<?php } ?>
	<?php } ?>
	</datalist>
	</p>
	<input type="button" id="btn_chat" name="toggle" value="chat" />

Next create a div for the chat box. This is where all the conversations will show up.

<div id="chat_div">
</div>

Next, write the jquery code that will serve as the processor for all the stuff which we are going to do in the chat box. And that includes: selecting the receiver of the message, saving the message into the database, updating the contents of the chatbox so that the most recent messages will be previewed without refreshing the whole page.

First, let’s set what we want to do once the page loads.

$(function(){

$('#chat_div').hide();  setInterval(load_messages, 2500); var username = $.trim($('#username').val()); var box = null;

});

Here’s what the code above does:

  • $(function(){ .. });  – the built in jquery function which serves as an initializer. Its equivalent to the document.ready() function in javascript. Anything which goes inside it will get executed once the page loads
  • $(‘#chat_div’).hide(); – we hide the chat box div since the recent chat messages from the database will get loaded into the div which is not enclosed in the chat box
  • setInterval(load_messages, 2500); – we call the load_messages() function every 2500 milliseconds
  • var username = $.trim($(‘#username’).val()); – we store the username of the user
  • var box = null; – we set the value of the chat box to null ensure that it doesn’t store anything on page load

 

Next, we set what happens when the user clicks on the chat button. Remember that the user must first select another user to chat with before clicking on the chat button. But I guess I didn’t include the code that checks if the text field indeed contains a username which is stored in the database. So you might as well include that while you’re following this tutorial.

$("#btn_chat").click(function(event, ui) {
		  
      if(box){
         box.chatbox("option", "boxManager").toggleBox();
       }else{
       
          box = $("#chat_div").chatbox({id: username, user:{key : username}, title : "chat", 
                                                messageSent : function(id, user, msg){
													
	 $.post('send_message.php', {'username': username, 'sendto' : $.trim($('#chatwith').val()), 'message' : msg});
													
          $("#chat_div").chatbox("option", "boxManager").addMsg(id, msg);
                                                }});
              }
          });

Here’s what the code above does:

  • box.chatbox(“option”, “boxManager”).toggleBox(); – toggles the chat box. When the user clicks on the chat button for the first time the chat box shows up. And when the user clicks on it again, it hides.
  • box = $(“#chat_div”).chatbox(); – setting the options for the chat box.
      • id – the id of the user who currently uses the chat box
      • user – json string which stores the name of the current user
      • title – title of the chat box. In facebook the title is the name of the user you are chatting with
      • messageSent – what you want to do once the user sends the message(pressing enter). The function assigned to this variable has 3 return values. The id, user, and msg 
  • $.post(); – we call up a php script which inserts the message into the database. In the code above, we passed in 3 arguments: the sender, receiver, and message. Scroll down to the latter part of this tutorial to view the code for inserting the message into the database
  • $(“#chat_div”).chatbox(“option”, “boxManager”).addMsg(id, msg); – lastly we call up the addMsg() function which appends the name of the user and the message into the chat box

 

Next, write the function which calls up the php script which loads up the recent messages from the database. Scroll down to the latter part of this tutorial to view the code of the load_messages.php script. Remember that this is the function that we call from the setInterval() function so that it will be called up every 2500 milliseconds.

 function load_messages(){
	$('#chat_div').load('load_messages.php');
 }

Next, create a new php file and name it send_message.php. The code is pretty self-explanatory, it’s the one that we use to save the user information, message and current date into the database.

<?php
require_once('tutorials_config.php');

$username = clean($_POST['username']);
$sendto = clean($_POST['sendto']);
$message = clean($_POST['message']);
$date = date('Y-m-d');

$send_message = $db->query("INSERT INTO chat_box SET sender='$username', sendto='$sendto', message='$message', date_sent='$date'");
?>


<?php
function clean($str){
	return trim(mysql_real_escape_string($str));
}
?>

Next, create a new php file again and name it load_messages.php. This one is also self-explanatory, we just fetch the recent messages, and sender from the database. We only fetch the messages which has the same date as the current date.

<?php
require_once('tutorials_config.php');

$user = $_SESSION['user_logs'];
$date = date('Y-m-d');
$messages = $db->get_results("SELECT * FROM chat_box WHERE date_sent='$date' AND sendto='$user' OR sender='$user'");

if(!empty($messages)){
foreach($messages as $v){
?>


<b><?php echo $v->sender; ?> :</b> <?php echo $v->message; ?><br/>
	

<?php } ?>
<?php } ?>

 

Output
Here’s a sample output. Yep! that’s me talking to myself just to test if its really working. Of course, the auto-suggest didn’t work in Chrome, so I had to type the name manually.

image

 

Conclusion
I guess that’s it for this tutorial. You’ve learned how to create a very simple chat box using jquery and php. If you like this tutorial, please don’t forget to share it. Thanks for reading!