<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ajax &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/ajax/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Data Compression with Run-length Encoding</title>
		<link>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/</link>
		<comments>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 09:08:06 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Algorithmic efficiency]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Bzip2]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[data compression algorithms]]></category>
		<category><![CDATA[faster services]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[lossless data compression algorithm]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[programmer]]></category>
		<category><![CDATA[run-length algorithm]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[This algorithm]]></category>
		<category><![CDATA[virtual machine]]></category>
		<category><![CDATA[web server]]></category>

		<guid isPermaLink="false">/?p=2594</guid>
		<description><![CDATA[Introduction No matter how fast today&#8217;s computers and networks are, the users will constantly need faster and faster services. To reduce the volume of the transferred data we usually use some sort of compression. That is why this computer sciences area will be always interesting to research and develop. There are many data compression algorithms, &#8230; <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Run-length Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>No matter how fast today&#8217;s computers and networks are, the users will constantly need faster and faster services. To reduce the volume of the transferred data we usually use some sort of compression. That is why this computer sciences area will be always interesting to research and develop.</p>
<p>There are many data compression algorithms, some of them lossless, others lossy, but their main goal aways will be to spare storage space and traffic. These algorithms are very useful when talking about data transfer between two distant places. Perhaps the best example is the transfer between a web server and a browser.</p>
<p>In the last few years a lot of research has been done on compressing files, executed on the client side. Such files are javascript, css, htmls and images. In fact servers and clients already have some techniques to compress data, like using <a href="http://www.gzip.org/" title="The gzip home page" target="_blank">GZIP</a> for instance, that can dramatically decrease the transfer. In the other hand there are lots of tools and tricks in order to decrease the size of the data.</p>
<p>Actually when a file is executed by the client&#8217;s virtual machine, it doesn&#8217;t matter how &#8220;beautifully&#8221; it is formatted from a programmer&#8217;s point of view. Thus the spaces, tabs and the new lines don&#8217;t bring any significant information for the environment. That is why such compressing tools like <a href="http://developer.yahoo.com/yui/compressor/" title="YUI Compressor" target="_blank">YUI Compressor</a>, <a href="http://code.google.com/closure/compiler/" title="Closure Compiler - Google Code" target="_blank">Google Closure Compiler</a>, etc. remove those symbols. Well, they can achieve even more in order to improve the compression rate. In this post I won&#8217;t cover this, but this shows how important data compression algorithms are.</p>
<p>It would be great if we could just compress data with some tool. Unfortunately this is not the case and usually the compression rate depends on the data itself. It is obvious that the choice of data compression algorithm depends mainly on the data and first of all we must explore the data.</p>
<p>Here I&#8217;ll cover one very simple lossless data compression algorithm called &#8220;run-length encoding&#8221; that can be very useful in some cases.</p>
<figure id="attachment_2618" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/Run-lengthEncoding1.png"><img src="/wp-content/uploads/2012/01/Run-lengthEncoding1.png" alt="Run-length Encoding" title="Run-length Encoding" width="620" class="size-full wp-image-2618" srcset="/wp-content/uploads/2012/01/Run-lengthEncoding1.png 978w, /wp-content/uploads/2012/01/Run-lengthEncoding1-300x129.png 300w" sizes="(max-width: 978px) 100vw, 978px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Overview</h2>
<p>This algorithm consists of replacing large sequences of repeating data with only one item of this data followed by a counter showing how many times this item is repeated. To become clearer let’s see a string example.</p>
<pre lang="PHP">
aaaaaaaaaabbbaxxxxyyyzyx
</pre>
<p>This string&#8217;s length is <strong>24</strong> and as we can see there are lots of repetitions. Using the run-length algorithm, we replace any run with shorter string followed by a counter.</p>
<pre lang="PHP">
a10b3a1x4y3z1y1x1
</pre>
<p>The length of this string is <strong>17</strong>, which is approximately <strong>70%</strong> of the initial length. <span id="more-2594"></span>Obviously this is not the optimal way to compress the given string. For instance we don&#8217;t need to use the digit “1” when the character is repeated only once. In some cases this approach can increase the length of the initial string which is exactly the opposite of what we need. In this case we’ll get the string bellow.</p>
<pre lang="PHP">
a10b3ax4y3zyx
</pre>
<p>Now the length of the resulting string is <strong>13</strong>, which is <strong>54%</strong> of the initial length! A variation of the example above is not to keep a counter of the repetitions of the character, but their position instead. Thus the initial string will be compressed as follows.</p>
<pre lang="PHP">
a0b10a13x14y18z21y22x23
</pre>
<p>Which of these two approaches you&#8217;ll use depends on the goal. In the second case we can achieve a good optimization of <a href="/2011/12/26/computer-algorithms-binary-search/" title="Computer Algorithms: Binary Search">binary search</a>.</p>
<p>It is clear that this algorithm is not only applicable on strings. We can achieve very good results on arrays. A typical example is the transfer of <a href="http://www.json.org/" title="JSON" target="_blank">JSON</a> from a server to a client. Then if there are large sequences of repeating data we can achieve great results.</p>
<h2>Implementation</h2>
<p>The implementation bellow is assuming that we&#8217;re compressing a string and it&#8217;s written on PHP. However the nature of this algorithm doesn&#8217;t restrict us to use only strings. As I said before with slight modifications we can use it with other data structures. It is important only to understand that the run-length algorithm is very useful on large sequences of repeating elements, no matter characters or array items.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = $j = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
			
			if ($i) 
				$output .= $j;
				
			$output .= $msg[$i];
				
			$prev = $msg[$i];
			
			$j = 0;
		}
		$j++;
		$i++;
	}
	
	$output .= $j;
	
	return $output;
}

// a10b3a1x4y3z1y1x1
echo run_length_encode($message);
</pre>
<p>And slightly optimized.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = $j = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
			
			if ($i && $j > 1) 
				$output .= $j;
				
			$output .= $msg[$i];
				
			$prev = $msg[$i];
			
			$j = 0;
		}
		$j++;
		$i++;
	}
	
	if ($j > 1)
		$output .= $j;
	
	return $output;
}

// a10b3ax4y3zyx
echo run_length_encode($message);
</pre>
<p>Finally a small change &#8211; now we store the position of the character.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
				
			$output .= $msg[$i] . $i;
				
			$prev = $msg[$i];
			
		}

		$i++;
	}
	
	return $output;
}

// a0b10a13x14y18z21y22x23
echo run_length_encode($message);
</pre>
<h2>Complexity and Data Compression</h2>
<p>We&#8217;re used to talk about complexity of an algorithm measuring time and we usually try to find the fastest implementation, like in search algorithms. Here it is not so important to compress data quickly, but to compress as much as possible so the output is as small as possible without lossing data. A great feature of run-length encoding is that this algorithm is easy to implement.</p>
<h2>Application</h2>
<p>We can use run-length encoding in many cases. It is commonly used to compress images and is very successful when we deal only with black and white images. Here I&#8217;ll cover another use case that I only mentioned above. Let&#8217;s say we have to transfer a very large array of data to our AJAX-powered application using JSON. Let&#8217;s say also that the data are some years, for instance the years of the premiere of a movie. There are lots of movies with a premiere in the same year, thus although the data is sorted, we actually can&#8217;t have any benefit. More important is that we have large sequences of data. Here we can use run-length encoding.</p>
<pre lang="PHP">
$data = array(
	0 	=> 1991,
	1 	=> 1991,
	...
	2223 	=> 1991,
	2224 	=> 1992,
	...
	19298 	=> 1995,
	19299 	=> 1996,
	...
);
</pre>
<p>As you can see to transfer the whole array can be a nightmare, especially on slow networks. It is better to compress it (i.e. with PHP&#8217;s <a href="http://php.net/manual/en/function.json-encode.php" title="PHP: json_encode" target="_blank">json_encode</a>).</p>
<pre lang="PHP">
// {"0":1991,"1":1991, ..., "2223":1991,"2224":1992, ..., "19298":1995,"19299":1996, ...}
echo json_encode($data);
</pre>
<p>After running run-length encoding we can receive something like the following array (note that these are only sample data and it&#8217;s up to you to decide which is the best format to store data).</p>
<pre lang="PHP">
$data = array(
	0 => array(1991, 2224),
	1 => array(1992, 3948),
	2 => array(1995, 2398),
	3 => array(1996, 3489),
);
</pre>
<p>And the JSON output.</p>
<pre lang="PHP">
// [[1991,2224],[1992,3948],[1995,2398],[1996,3489]]
echo json_encode($data);
</pre>
<p>Note that if the data is sorted we can achieve great success compressing it!!! This approach can be used for images, graphics or map coordinates.</p>
<p>This is only one example of how data compression can be useful in our daily work. Although the communication between the server and the client can be optimized and compressed, we can improve it. In other words we&#8217;re not always sure that the opposite side supports compression.</p>
<p>Well, it&#8217;s true that the client has to decompress the data, which can also be slow. Now in the first case we have only the time to transfer, as on the diagram bellow.</p>
<figure id="attachment_2609" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png"><img src="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png" alt="Data Transfer Without Compression" title="Data Transfer Without Compression" width="620" class="size-full wp-image-2609" srcset="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png 957w, /wp-content/uploads/2012/01/DataTransferWithoutCompression-300x54.png 300w" sizes="(max-width: 957px) 100vw, 957px" /></a><figcaption class="wp-caption-text">Time to transfer data without compression!</figcaption></figure>
<p>In the second case, we should sum the time for compression, transfer and decompression.</p>
<figure id="attachment_2610" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DataTransferwithCompression.png"><img src="/wp-content/uploads/2012/01/DataTransferwithCompression.png" alt="Data Transfer with Compression" title="Data Transfer with Compression" width="620" class="size-full wp-image-2610" srcset="/wp-content/uploads/2012/01/DataTransferwithCompression.png 953w, /wp-content/uploads/2012/01/DataTransferwithCompression-300x59.png 300w" sizes="(max-width: 953px) 100vw, 953px" /></a><figcaption class="wp-caption-text">Time to send data with compression!</figcaption></figure>
<p>All this is important, but in general data compression can be handy in many cases in our daily work. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Object Oriented JavaScript: Inheritance</title>
		<link>/2011/05/30/object-oriented-javascript-inheritance/</link>
		<comments>/2011/05/30/object-oriented-javascript-inheritance/#comments</comments>
		<pubDate>Mon, 30 May 2011 09:43:53 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[web development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Class]]></category>
		<category><![CDATA[code sample]]></category>
		<category><![CDATA[code snippet]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Inheritance]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Literal]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[Object-oriented programming]]></category>
		<category><![CDATA[objects]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[oop javascript]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Software engineering]]></category>

		<guid isPermaLink="false">/?p=2314</guid>
		<description><![CDATA[Objects and JavaScript JavaScript, being a functional language, differs from most of the procedural/object oriented languages we know. The object oriented approach in JavaScript is rather strange. However there is much power in making objects! The syntax is really odd and there are several approaches. Literal Notation As many of you may know the most &#8230; <a href="/2011/05/30/object-oriented-javascript-inheritance/" class="more-link">Continue reading <span class="screen-reader-text">Object Oriented JavaScript: Inheritance</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/03/02/javascript-inheritance-example/" rel="bookmark" title="JavaScript inheritance example">JavaScript inheritance example </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Objects and JavaScript</h2>
<p><a href="/tag/javascript/" title="JavaScript on Stoimen.com">JavaScript</a>, being a functional language, differs from most of the procedural/object oriented languages we know. The object oriented approach in JavaScript is rather strange. However there is much power in making objects! The syntax is really odd and there are several approaches.</p>
<h2>Literal Notation</h2>
<p>As many of you may know the most used notation is the JSON (JavaScript Object Notation).</p>
<pre lang="javascript">
{ 'key1' : 'val1'
, 'key2' : 'val2'
, 'key3' : 'val3'
}
</pre>
<p>Of course this is the very basic example. You can use as value any JavaScript object &#8211; another similar object or a function.</p>
<pre lang="javascript">
{ 'key1' : 'val1'
, 'key2' : { 'inner_key1' : 'inner_val1' }
, 'key3' : function() {
			return 10 + 5;
		 }
}
</pre>
<p>The two examples above are showing an anonymous object in JavaScript, but you can assign this code to some variable.</p>
<pre lang="javascript">
var myObject = 
	{ 'key1' : 'val1'
	, 'key2' : 'val2'
	, 'key3' : 'val3'
	}
</pre>
<p>or </p>
<pre lang="javascript">
var myObject =
	{ 'key1' : 'val1'
	, 'key2' : { 'inner_key1' : 'inner_val1' }
	, 'key3' : function() {
				return 10 + 5;
			 }
	}
</pre>
<p>and then you can call the properties of these objects with the &#8216;.&#8217; operator:</p>
<pre lang="javascript">
myObject.key1;
myObject.key2.inner_key1;
myObject.key3();
</pre>
<p>So far so good &#8211; this is the literal object notation in JavaScript. However there is another &#8220;objects&#8221; in JavaScript.<br />
<span id="more-2314"></span></p>
<h2>Objects and Functions in JavaScript</h2>
<p>Actually in JS the functions are also objects (classes). So you can define a function and then define another function inside or use the &#8220;this&#8221; operator.</p>
<pre lang="javascript">
var a = function(name)
{
	this.name = name;
	
	this.print = function() {
		alert(this.name);	
	}
}
</pre>
<p>Then you can make a new instance of this &#8220;class&#8221;.</p>
<pre lang="javascript">
var myObject = new a('hello world');
var anotherObject = new a('some test');

myObject.print(); // will print the string "hello world"
anotherObject.print(); // will print the string "some test"
</pre>
<p>Thus the function <strong>&#8220;a&#8221;</strong> defined within the code <strong>&#8220;var a = function(name) &#8230;&#8221;</strong> is a class in JavaScript. You can make instances (objects) of this class with the &#8220;new&#8221; operator.</p>
<p>You can use another notation for defining the function &#8220;a&#8221;, so both can be used and it&#8217;s up to you to decide which one is more convenient.</p>
<pre lang="javascript">
function a(name) 
{
	this.name = name;
	
	this.print = function() {
		alert(this.name);	
	}	
}
</pre>
<h2>Prototypes</h2>
<p>JS gives you more power. In most of the languages you&#8217;ve to define the class first and then make objects. In JS you can define a &#8220;class&#8221; then make some objects and then add some properties to the class by using the prototype.</p>
<pre lang="javascript">
var a = function(name) 
{
	this.name = name;
}

var myObj = new a('hello world');

a.prototype.print = function() {
	alert(this.name);	
}

myObj.print();
</pre>
<p>So you can see how you can add functions and properties to an already defined class using the prototype. Thus you can call the &#8220;print&#8221; function on the myObj object.</p>
<h2>Inheritance</h2>
<p>The prototype built-in property can be used to make use of one of the main OOP features &#8211; inheritance. </p>
<pre lang="javascript">
var SuperClass = function()
{
	this.superFunction = function() {
		return 'function in Super Class';	
	}
}

var sup = new SuperClass();
sup.superFunction(); // will return the string "function in Super Class"
</pre>
<p>Now you can add one more class and set its prototype to the SuperClass</p>
<pre lang="javascript">
var SubClass = function()
{
	this.subFunction = function() {
		return 'function in Sub Class';	
	}	
}

SubClass.prototype = new SuperClass();
</pre>
<p>Thus you make SubClass inherit from SuperClass. Now you can call the SuperClass properties from any SubClass object.</p>
<pre lang="javascript">
var sub = new SubClass();
sub.superFunction(); // will return the string "function in Super Class"
sub.subFunction(); // will return the string "function in Sub Class"
</pre>
<p>Even more! You can add properties to the super class with prototype.</p>
<pre lang="javascript">
SuperClass.prototype.myFunc = function() {
	return 'my new function';	
}
</pre>
<p>And then call it from the sub class:</p>
<pre lang="javascript">
sub.myFunc(); // will return the string "my new function"
</pre>
<h2>Override a Function</h2>
<p>What happens if you have the same function name in both classes. Actually this overrides the method in the sub class.</p>
<pre lang="javascript">
var SuperClass = function()
{
	this.myFunc = function() {
		return 'function in Super Class';	
	}
}

var SubClass = function()
{
	this.myFunc = function() {
		return 'function in Sub Class';	
	}	
}

SubClass.prototype = new SuperClass();

var sub = new SubClass();
sub.myFunc(); // will return the string "function in Sub Class"
</pre>
<p>while </p>
<pre lang="javascript">
var sup = new SuperClass();
sup.myFunc(); // will return the string "function in Super Class"
</pre>
<h2>Conclusion</h2>
<p>Now you know there are classes, inheritance and overrides in JavaScript &#8211; thus you can improve your object oriented JavaScript!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/03/02/javascript-inheritance-example/" rel="bookmark" title="JavaScript inheritance example">JavaScript inheritance example </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/05/30/object-oriented-javascript-inheritance/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>jQuery.unbind()</title>
		<link>/2011/04/05/jquery-unbind/</link>
		<comments>/2011/04/05/jquery-unbind/#comments</comments>
		<pubDate>Tue, 05 Apr 2011 08:51:08 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Button]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Event]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[HTTP cookie]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery method]]></category>
		<category><![CDATA[Microsoft Binder]]></category>
		<category><![CDATA[obvious solution]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[possible solution]]></category>
		<category><![CDATA[RME]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[unbind]]></category>
		<category><![CDATA[User interface]]></category>
		<category><![CDATA[Widgets]]></category>

		<guid isPermaLink="false">/?p=2240</guid>
		<description><![CDATA[Binding Problems Typically in jQuery when you bind an HTML element with some event this event is fired every time the user (client) triggers it. Thus when you&#8217;ve a click event attached on a button you can click it as many times as you want. In some rare cases this can be tricky. Let&#8217;s imagine &#8230; <a href="/2011/04/05/jquery-unbind/" class="more-link">Continue reading <span class="screen-reader-text">jQuery.unbind()</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2009/12/30/jquery-live-vs-bind-performance/" rel="bookmark" title="jQuery live() vs bind() performance">jQuery live() vs bind() performance </a></li>
<li><a href="/2009/05/25/remove-dom-element-with-jquery/" rel="bookmark" title="Remove DOM Element with JQuery">Remove DOM Element with JQuery </a></li>
<li><a href="/2009/10/21/event-driven-programming-with-jquery-part-2-events-in-jquery/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 2). Events in jQuery.">Event driven programming with jQuery &#8211; (part 2). Events in jQuery. </a></li>
<li><a href="/2009/10/22/event-driven-programming-with-jquery-part-3-what-is-a-module/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 3). What is a module?">Event driven programming with jQuery &#8211; (part 3). What is a module? </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Binding Problems</h2>
<figure id="attachment_2254" style="width: 460px" class="wp-caption aligncenter"><a href="http://jquery.com/" target="_blank"><img class="size-full wp-image-2254" title="jquery applications" src="/wp-content/uploads/2011/04/jquery_applications.jpg" alt="jQuery JavaScript Library" width="460" height="240" srcset="/wp-content/uploads/2011/04/jquery_applications.jpg 460w, /wp-content/uploads/2011/04/jquery_applications-300x156.jpg 300w" sizes="(max-width: 460px) 100vw, 460px" /></a><figcaption class="wp-caption-text">jQuery JavaScript Library</figcaption></figure>
<p>Typically in <a title="jQuery on stoimen.com/blog" href="/tag/jquery/">jQuery</a> when you bind an <a title="HTML on stoimen.com/blog" href="/tag/html/">HTML</a> element with some event this event is fired every time the user (client) triggers it. Thus when you&#8217;ve a click event attached on a button you can click it as many times as you want. In some rare cases this can be tricky. Let&#8217;s imagine the following scenario.</p>
<ol>
<li>The user clicks on a &#8220;vote&#8221; button.</li>
<li>Some AJAX calls are performed.</li>
<li>After a successful AJAX call you setup a cookie to deny further votes from this machine.</li>
</ol>
<p>This seems to be pretty well known scenario, but as the click event is attached to the button there is enough time to click several times on the &#8220;vote&#8221; button and to vote several times. In this case before the cookie is set the user can vote more than once.<span id="more-2240"></span></p>
<h3>Demo</h3>
<p><iframe frameborder="0" scrolling="no" src="http://stoimen.com/projects/jquery.unbind/example1.php" style="border:1px solid #ccc;width:500px"></iframe></p>
<p>So one possible solution is to unbind the click event. In jQuery terms this is done by &#8230;</p>
<h2>$.unbind()</h2>
<p>With this method you can simply unbind the &#8220;click&#8221; event or whatever event there is attached on the desired HTML element. So now in the first case we had:</p>
<pre lang="javascript">
$(document).ready(function() {
    $('input').click(function() {
        $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php'
               , success : function() {
                    $('p').append('You\'ve voted successfully!<br />');
               }    
        }); 
    }); 
});
</pre>
<p>Now you can replace the code above with:</p>
<pre lang="javascript">
$(document).ready(function() {
    $('input').click(function() {
        $('input').unbind();
        $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php'
               , success : function() {
                    $('p').append('You\'ve voted successfully!<br />');
               }    
        }); 
    }); 
});
</pre>
<p>As you can see on the demo here now the button cannot be clicked more than once.</p>
<h3>Demo</h3>
<p><iframe frameborder="0" scrolling="no" src="http://stoimen.com/projects/jquery.unbind/example2.php" style="border:1px solid #ccc;width:500px"></iframe></p>
<h2>Cookies + unbind()</h2>
<p>There is a problem however. After reloading the page the event is attached again, so the user can click on the button once more. The obvious solution is to combine both the cookie and the unbind() as shown in the following pseudo code.</p>
<pre lang="javascript">
$(document).ready(function() {
    if (cookie is not set) { 
        $('input').click(function() {
            $('input').unbind();
            $.ajax({ url : 'http://stoimen.com/projects/jquery.unbind/example1.php'
                   , success : function() {
                        $('p').append('You\'ve voted successfully!<br />');
                        set cookie
                   }    
            }); 
        });
    } 
});
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2009/12/30/jquery-live-vs-bind-performance/" rel="bookmark" title="jQuery live() vs bind() performance">jQuery live() vs bind() performance </a></li>
<li><a href="/2009/05/25/remove-dom-element-with-jquery/" rel="bookmark" title="Remove DOM Element with JQuery">Remove DOM Element with JQuery </a></li>
<li><a href="/2009/10/21/event-driven-programming-with-jquery-part-2-events-in-jquery/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 2). Events in jQuery.">Event driven programming with jQuery &#8211; (part 2). Events in jQuery. </a></li>
<li><a href="/2009/10/22/event-driven-programming-with-jquery-part-3-what-is-a-module/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 3). What is a module?">Event driven programming with jQuery &#8211; (part 3). What is a module? </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/04/05/jquery-unbind/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Diving into Node.js &#8211; A Long Polling Example</title>
		<link>/2010/12/02/diving-into-node-js-a-long-polling-example/</link>
		<comments>/2010/12/02/diving-into-node-js-a-long-polling-example/#comments</comments>
		<pubDate>Thu, 02 Dec 2010 09:51:48 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[chat-like applications]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[Hypertext Transfer Protocol]]></category>
		<category><![CDATA[Internet protocols]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[long polling server]]></category>
		<category><![CDATA[Node]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[real time data]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[typical web server]]></category>
		<category><![CDATA[web developers]]></category>
		<category><![CDATA[web server]]></category>
		<category><![CDATA[web servers]]></category>
		<category><![CDATA[World Wide Web]]></category>
		<category><![CDATA[XMLHttpRequest]]></category>

		<guid isPermaLink="false">/?p=2041</guid>
		<description><![CDATA[Node.js vs. The World What is typical for most of the web servers is that they listen for requests and respond as quickly as possible on every one of them. In fact the speed of the response is one of the main targets of optimization for developers. Fast servers are what everyone needs. From web &#8230; <a href="/2010/12/02/diving-into-node-js-a-long-polling-example/" class="more-link">Continue reading <span class="screen-reader-text">Diving into Node.js &#8211; A Long Polling Example</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/11/19/diving-into-node-js-very-first-app/" rel="bookmark" title="Diving into Node.js &#8211; Very First App">Diving into Node.js &#8211; Very First App </a></li>
<li><a href="/2010/11/16/diving-into-node-js-introduction-and-installation/" rel="bookmark" title="Diving into Node.js &#8211; Introduction &#038; Installation">Diving into Node.js &#8211; Introduction &#038; Installation </a></li>
<li><a href="/2010/03/23/read-remote-file-content-type-with-zend_http_client/" rel="bookmark" title="Read Remote File Content-Type with Zend_Http_Client">Read Remote File Content-Type with Zend_Http_Client </a></li>
<li><a href="/2011/04/13/post-with-zend_http_client/" rel="bookmark" title="POST with Zend_Http_Client">POST with Zend_Http_Client </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Node.js vs. The World</h2>
<p><a href="/wp-content/uploads/2010/11/node-js.jpg"><img class="aligncenter size-full wp-image-2088" title="node js" src="/wp-content/uploads/2010/11/node-js.jpg" alt="" width="445" height="193" srcset="/wp-content/uploads/2010/11/node-js.jpg 445w, /wp-content/uploads/2010/11/node-js-300x130.jpg 300w" sizes="(max-width: 445px) 100vw, 445px" /></a></p>
<p>What is typical for most of the web servers is that they listen for requests and respond as quickly as possible on every one of them. In fact the speed of the response is one of the main targets of optimization for developers. Fast servers are what everyone needs. From web developers to website visitors!</p>
<p>In the field of the that battle different web servers have different &#8220;weapons&#8221; to gain time. While this is useful in most of the cases, when it comes to a chat-like applications and <a title="Node.js" href="http://nodejs.org/" target="_blank">Node.js</a> approaches, the response is not always immediately returned. As I described in my <a title="Diving into Node.js – Very First App" href="/2010/11/19/diving-into-node-js-very-first-app/" target="_self">posts</a> until now about Node.js, a simple web server may wait for an event to be emitted, and than return the response.<span id="more-2041"></span></p>
<p>I wrote about <a title="Diving into Node.js – Very First App" href="/2010/11/19/diving-into-node-js-very-first-app/" target="_self">how to write the very first server</a>, but than I didn&#8217;t described how to make a &#8220;non-responding&#8221; server. By the term &#8220;non-responding&#8221; I mean a server that responds not immediately after it has received and parsed/executed the request.</p>
<p>A typical web server, responding immediately on every request, written with Node, this may look like so:</p>
<pre lang="javascript">var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
</pre>
<p>The code that shows us that the request is executed and responds in these lines:</p>
<pre lang="javascript">  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
</pre>
<p>Actually by commenting/removing those lines you&#8217;ll get a server that simply doesn&#8217;t respond &#8211; ever! This of course is not the main goal, but you can start from somewhere.</p>
<pre lang="javascript">var http = require('http');
http.createServer(function (req, res) {
  // res.writeHead(200, {'Content-Type': 'text/plain'});
  // res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
</pre>
<p>This is how you can hold for a while. Perhaps putting these lines in a conditional statement and periodically checking for some event to occur will do the job.</p>
<pre lang="javascript">var http = require('http');
http.createServer(function (req, res) {
  if (something) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World\n');
  }
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
</pre>
<h2>Looping Server</h2>
<p>As described in the code above if you put the respond into a conditional you can possibly return the response after some event has fired. The only thing is to periodically loop and check for this condition to be true. Assuming your server&#8217;s code is in server.js, started with the &#8220;node server.js&#8221; command, you&#8217;ve to put this code into it:</p>
<pre lang="javascript" escaped="true">var http = require("http"),
    fs	 = require("fs");  

// we create a server with automatically binding
// to a server request listener
http.createServer(function(request, response) {
	checkFile(request, response);
}).listen(8124);

function checkFile(request, response)
{
	var date = new Date();
	if (date-request.socket._idleStart.getTime() &gt; 59999) {
		response.writeHead(200, {
			'Content-Type'   : 'text/plain',
			'Access-Control-Allow-Origin' : '*'
		});

		// return response
		response.write('OK', 'utf8');
		response.end();
	}

	// we check the information from the file, especially
	// to know when it was changed for the last time
	fs.stat('filepath', function(err, stats) {
		// if the file is changed
		if (stats.mtime.getTime() &gt; request.socket._idleStart.getTime()) {
			// read it
			fs.readFile('filepath', 'utf8', function(err, data) {
				// return the contents
				response.writeHead(200, {
					'Content-Type'   : 'text/plain',
					'Access-Control-Allow-Origin' : '*'
				});

				// return response
				response.write(data, 'utf8');
				response.end();

				// return
				return false;
			});
		}
	});	

	setTimeout(function() { checkFile(request, response) }, 10000);
};
</pre>
<p>Note: you must change &#8220;filepath&#8221; with an existing file path in your system.</p>
<p>Here we can read periodically the file&#8217;s mtime, which is the modify time. Thus whenever the file is changed the server will return the response. It&#8217;s interesting to note that if no change occurs within the timeout period you&#8217;ve to return some status message as we did in those lines:</p>
<pre lang="javascript" escaped="true">        
var date = new Date();
if (date-request.socket._idleStart.getTime() > 59999) {
	response.writeHead(200, {
		'Content-Type'   : 'text/plain',
		'Access-Control-Allow-Origin' : '*'
	});
	
	// return response
	response.write('OK', 'utf8');
	response.end();
}
</pre>
<p>The client side should long poll this server. The example bellow is written in jQuery. The only &#8220;special&#8221; thing is that after receiving the response, you must call the server again.</p>
<h3>The Client</h3>
<p>The client is nothing new to the jQuery/JavaScript community except you must call again the server when the response is returned:</p>
<pre lang="javascript">function callNode() {
    $.ajax({
        cache : false,
		// setup the server address
        url : 'http://www.example.com:8124/',
        data : {},
        success : function(response, code, xhr) {

            if ('OK' == response) {
            	callNode();
                return false;
            }

            // do whatever you want with the response
            ...

            // make new call
            callNode();
        }
    });
};
callNode();
</pre>
<h2>Summary</h2>
<p>As Node can hold the response, the only thing you should do is to check periodically for something as in this example this was a file change. Than it&#8217;s important to change the client so it can call the server after the response from it is received.</p>
<p>Typically Node can be used for chat-like applications or whatever apps that must deliver real time data, but for sure it is really great software.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/11/19/diving-into-node-js-very-first-app/" rel="bookmark" title="Diving into Node.js &#8211; Very First App">Diving into Node.js &#8211; Very First App </a></li>
<li><a href="/2010/11/16/diving-into-node-js-introduction-and-installation/" rel="bookmark" title="Diving into Node.js &#8211; Introduction &#038; Installation">Diving into Node.js &#8211; Introduction &#038; Installation </a></li>
<li><a href="/2010/03/23/read-remote-file-content-type-with-zend_http_client/" rel="bookmark" title="Read Remote File Content-Type with Zend_Http_Client">Read Remote File Content-Type with Zend_Http_Client </a></li>
<li><a href="/2011/04/13/post-with-zend_http_client/" rel="bookmark" title="POST with Zend_Http_Client">POST with Zend_Http_Client </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/12/02/diving-into-node-js-a-long-polling-example/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Diving into Node.js &#8211; Very First App</title>
		<link>/2010/11/19/diving-into-node-js-very-first-app/</link>
		<comments>/2010/11/19/diving-into-node-js-very-first-app/#comments</comments>
		<pubDate>Fri, 19 Nov 2010 09:55:36 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[web development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Computer networking]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[Hypertext Transfer Protocol]]></category>
		<category><![CDATA[Internet protocols]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[Localhost]]></category>
		<category><![CDATA[Network architecture]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[port While]]></category>
		<category><![CDATA[server on nodejs]]></category>
		<category><![CDATA[Server-side JavaScript]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[unix]]></category>

		<guid isPermaLink="false">/?p=2066</guid>
		<description><![CDATA[What do I have till now? After Node.js is istalled, described in my previous post, I can simply run this command: stoimenpopov:~# node server.js and this will start the server with the code within server.js. But what&#8217;s the code of server.js? Following the instructions of Node&#8217;s homepage and most of the tutorials I&#8217;ve found, I &#8230; <a href="/2010/11/19/diving-into-node-js-very-first-app/" class="more-link">Continue reading <span class="screen-reader-text">Diving into Node.js &#8211; Very First App</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/12/02/diving-into-node-js-a-long-polling-example/" rel="bookmark" title="Diving into Node.js &#8211; A Long Polling Example">Diving into Node.js &#8211; A Long Polling Example </a></li>
<li><a href="/2010/11/16/diving-into-node-js-introduction-and-installation/" rel="bookmark" title="Diving into Node.js &#8211; Introduction &#038; Installation">Diving into Node.js &#8211; Introduction &#038; Installation </a></li>
<li><a href="/2010/03/23/read-remote-file-content-type-with-zend_http_client/" rel="bookmark" title="Read Remote File Content-Type with Zend_Http_Client">Read Remote File Content-Type with Zend_Http_Client </a></li>
<li><a href="/2011/04/13/post-with-zend_http_client/" rel="bookmark" title="POST with Zend_Http_Client">POST with Zend_Http_Client </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>What do I have till now?</h2>
<p>After Node.js is istalled, described in <a href="/2010/11/16/diving-into-node-js-introduction-and-installation/" target="_self">my previous post</a>, I can simply run this command:</p>
<blockquote><p>stoimenpopov:~# node server.js</p></blockquote>
<p>and this will start the server with the code within server.js. But what&#8217;s the code of server.js?</p>
<p>Following the instructions of <a title="Nodejs" href="http://nodejs.org/" target="_blank">Node&#8217;s homepage</a> and most of the tutorials I&#8217;ve found, I can simply copy/paste the code from the first lines of Node&#8217;s page:</p>
<pre lang="javascript">var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');</pre>
<p>There are several things I find interesting in this code, making it different from JavaScript as we know it. First of all what is</p>
<blockquote><p>var http = require(&#8216;http&#8217;)</p></blockquote>
<p>and why I need it? What is the purpouse of 8124 and 127.0.0.1?</p>
<p>Node is built in modules and to use one of them you must first include it with <strong>require</strong>. Just like the example above with require(&#8216;http&#8217;). In the same manner you can include every module of Node.</p>
<p>What are the Node&#8217;s modules are pretty well described in <a title="Node.js API" href="http://nodejs.org/docs/v0.2.5/api.html" target="_blank">the API page</a>. Well I&#8217;d like to say that the API page is quite insufficient. That is very bad, cause most of the code you&#8217;ll need developing a node.js applicatoin isn&#8217;t described/explained there.<span id="more-2066"></span></p>
<p>However is more than obvious that 8124 is the port, while 127.0.0.1 is the IP address of the server, which in this case is the localhost. Thus after running the server and typing http://127.0.0.1:8124/ into your browser you&#8217;ll get &#8220;Hello World&#8221;. This is not enough when the server is running on a remote machine, while you&#8217;ve to access it from your local computer.</p>
<h2>The first server</h2>
<p>As I described the code above shows you an example server. In fact the API page shows a slightly different code:</p>
<pre lang="javascript">var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');</pre>
<p>Here the line:</p>
<pre lang="javascript">}).listen(8124);</pre>
<p>omits the address of the server. It appears to be non-required and the server is supposed to listen on this machine on the given port. To be honest I&#8217;m not sure why you&#8217;ve to write the server address, except for limit the possible address to this one. However in my case the server was installed on a remote machine indeed, while I was trying to access it from my local machine. So here are some base steps to do before accomplishing this.</p>
<h3>1. Changing the IP address</h3>
<p>First of all you can omit the IP address. This can help you move the code from one server to another without changing the code.</p>
<pre lang="javascript">}).listen(8124, ip_address);</pre>
<p>possibly a better solution is:</p>
<pre lang="javascript">}).listen(8124);</pre>
<p>Node can listen on whatever port you say so this is up to you to decide which port should be opened.</p>
<h3>2. Opening the port</h3>
<p>While everything&#8217;s on the localhost you wont have problems with port opening. If you&#8217;d like to access it remotely however, you&#8217;ve to open the port. In other words http://127.0.0.1:8124/ is OK without port opening, but http://example.com:8124/ &#8211; is not!</p>
<p>To open a port in UNIX/Linux you&#8217;ve to type this command in the terminal:</p>
<pre lang="bash">iptables -A INPUT -p tcp --dport 8124 -j ACCEPT</pre>
<p>don&#8217;t forget to change the port number from 8124 to whatever port number you&#8217;re using.</p>
<h3>3. The first AJAX call</h3>
<p>We still cannot make the first AJAX call to the Node server. Here I&#8217;m using <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a> because of the easy AJAX interface.</p>
<pre lang="javascript">$(document).ready(function() {
	$.ajax({
    	// setup the server address
        url : 'http://example:8124/',
        success : function(response) {
        	// on success
        	alert(response);
		},
        error : function() {
        	// on error
        }
    });
});</pre>
<p>After executing this code in a browser there wont be a response. That is because of the remote AJAX calls restriction. To overcome this you&#8217;ve to change the returned header from the Node&#8217;s server, by adding this:</p>
<pre lang="javascript">'Access-Control-Allow-Origin' : '*'</pre>
<p>Now server.js will look like this:</p>
<pre lang="javascript">var http = require('http');

http.createServer(function (request, response) {
	response.writeHead(200, {
		'Content-Type': 'text/plain',
		'Access-Control-Allow-Origin' : '*'
	});
	response.end('Hello World\n');
}).listen(8124);</pre>
<p>you can now either load http://example.com:8124/ into your browser or to make the AJAX call. In both cases the answer will be &#8220;Hello World&#8221;</p>
<h2>Summary</h2>
<p>Now you have a very simple Node.js server. Well it is nothing special as it responses with &#8220;Hello World&#8221; on every request, but it works remotely.</p>
<p>Soon I&#8217;ll describe how to change the server so it can waits to respond until some event is emitted &#8211; which is the real power of Node.js.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/12/02/diving-into-node-js-a-long-polling-example/" rel="bookmark" title="Diving into Node.js &#8211; A Long Polling Example">Diving into Node.js &#8211; A Long Polling Example </a></li>
<li><a href="/2010/11/16/diving-into-node-js-introduction-and-installation/" rel="bookmark" title="Diving into Node.js &#8211; Introduction &#038; Installation">Diving into Node.js &#8211; Introduction &#038; Installation </a></li>
<li><a href="/2010/03/23/read-remote-file-content-type-with-zend_http_client/" rel="bookmark" title="Read Remote File Content-Type with Zend_Http_Client">Read Remote File Content-Type with Zend_Http_Client </a></li>
<li><a href="/2011/04/13/post-with-zend_http_client/" rel="bookmark" title="POST with Zend_Http_Client">POST with Zend_Http_Client </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/11/19/diving-into-node-js-very-first-app/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Diving into Node.js &#8211; Introduction &#038; Installation</title>
		<link>/2010/11/16/diving-into-node-js-introduction-and-installation/</link>
		<comments>/2010/11/16/diving-into-node-js-introduction-and-installation/#comments</comments>
		<pubDate>Tue, 16 Nov 2010 08:17:32 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[web development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Apache Corporation]]></category>
		<category><![CDATA[Apache HTTP Server]]></category>
		<category><![CDATA[application/server]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[classical chat server]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Google Chrome]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[Inter-process communication]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[normal server]]></category>
		<category><![CDATA[normal web server]]></category>
		<category><![CDATA[operating system]]></category>
		<category><![CDATA[Push technology]]></category>
		<category><![CDATA[Server-side JavaScript]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[typical web server]]></category>
		<category><![CDATA[Web browser]]></category>
		<category><![CDATA[web developer team]]></category>
		<category><![CDATA[web server]]></category>
		<category><![CDATA[web server example]]></category>
		<category><![CDATA[web serving functionality]]></category>
		<category><![CDATA[World Wide Web]]></category>

		<guid isPermaLink="false">/?p=2037</guid>
		<description><![CDATA[Why I Need Something Like Node.js? First of all the use of some software is needed not because of itself, but because of the need of some specific functionality. In my case this was the need of real time news feed. Of course there is a way to make this without Node.js, as I&#8217;ll describe &#8230; <a href="/2010/11/16/diving-into-node-js-introduction-and-installation/" class="more-link">Continue reading <span class="screen-reader-text">Diving into Node.js &#8211; Introduction &#038; Installation</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/12/02/diving-into-node-js-a-long-polling-example/" rel="bookmark" title="Diving into Node.js &#8211; A Long Polling Example">Diving into Node.js &#8211; A Long Polling Example </a></li>
<li><a href="/2010/11/19/diving-into-node-js-very-first-app/" rel="bookmark" title="Diving into Node.js &#8211; Very First App">Diving into Node.js &#8211; Very First App </a></li>
<li><a href="/2010/01/31/speed-up-the-javascript-it-can-change-dramatically-the-user-experience/" rel="bookmark" title="Speed up the JavaScript. It can change dramatically the user experience.">Speed up the JavaScript. It can change dramatically the user experience. </a></li>
<li><a href="/2010/01/11/what-should-be-optimized-in-one-web-page/" rel="bookmark" title="What should be optimized in one web page?">What should be optimized in one web page? </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Why I Need Something Like Node.js?</h2>
<p>First of all the use of some software is needed not because of itself, but because of the need of some specific functionality. In my case this was the need of real time news feed. Of course there is a way to make this without <a title="Node.js" href="http://nodejs.org/" target="_blank">Node.js</a>, as I&#8217;ll describe later in this post, but there are several disadvantages. However to begin from somewhere, let me explain what is Node.js.</p>
<h2>Introducing Node.js</h2>
<p>Perhaps the best way do describe what is Node.js is from its <a title="Node.js" href="http://nodejs.org/#about" target="_blank">about page</a>.</p>
<blockquote><p>Node&#8217;s goal is to provide an easy way to build scalable network programs. In the &#8220;hello world&#8221; web server example above, many client connections can be handled concurrently. Node tells the operating system (through epoll, kqueue, /dev/poll, or select) that it should be notified when a new connection is made, and then it goes to sleep. If someone new connects, then it executes the callback. Each connection is only a small heap allocation.</p>
<p>&#8230;</p></blockquote>
<p>In general Node is a program using the Google Chrome&#8217;s <a title="V8 JavaScript engine" href="http://code.google.com/p/v8/" target="_blank">V8 JavaScript</a> engine, which in turn is a program that can parse and execute code written in JavaScript. V8 is a very very interesting project itself. First of all from Google have developed this engine especially for one of his products &#8211; their browser <a title="Google Chrome" href="http://www.google.com/chrome" target="_blank">Chrome</a>. It pretends to be and by no means is one of the masterpieces of Google. It is fast and reliable engine, written in C++ and JavaScript, as <a title="V8 JavaScript engine on Wikipedia" href="http://en.wikipedia.org/wiki/V8_%28JavaScript_engine%29" target="_blank">Wikipedia&#8217;s page</a> says. Actually this code is open source and can be embedded in whatever application written in C++. Thus you can have in your application a JavaScript engine.<span id="more-2037"></span></p>
<p>Such kind of application/server is Node.js. With V8 embedded into, Node is intended to run on a machine and to serve some requests. Just like a normal web server, but with few differences. First of all Node is not only serving HTTP requests, but also TCP. Well I&#8217;m not so deep into this yet, but so far that works for me. What I need for now is its web serving functionality.</p>
<p>The way Node works, however is different from what we know from every other web server. Here it is a normal server in general:</p>
<p><a href="/wp-content/uploads/2010/11/client-server.png"></a><a href="/wp-content/uploads/2010/11/client-server.png"><img class="alignleft size-full wp-image-2053" title="client-server" src="/wp-content/uploads/2010/11/client-server.png" alt="Client Server" width="600" height="150" srcset="/wp-content/uploads/2010/11/client-server.png 600w, /wp-content/uploads/2010/11/client-server-300x75.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a></p>
<p>Whenever a request comes to the server, it tries to return the response as fast as possible. This is one of the main goals of every web developer team &#8211; to make the application as fast as possible. However in Node the things work different:</p>
<p><a href="/wp-content/uploads/2010/11/node-client-server.png"><img class="alignleft size-full wp-image-2058" title="node-client-server" src="/wp-content/uploads/2010/11/node-client-server.png" alt="Node.js Client Server Application" width="600" height="150" srcset="/wp-content/uploads/2010/11/node-client-server.png 600w, /wp-content/uploads/2010/11/node-client-server-300x75.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a></p>
<p>Here the server doesn&#8217;t return immediately the response, but holds as long as possible until some &#8220;event&#8221; occurs. You can thing of Node as a classical chat server. Until one of the peers doesn&#8217;t write a message, the other doesn&#8217;t receive anything.</p>
<blockquote><p>Some may be confused as how you can use both the typical web server, as Apache, with Node as another web server within the same page. The answer is &#8211; with AJAX. As you know thus you can have only one chunk of your page talking with the server &#8211; in this case the entire page is returned by Apache, but inside the page you can have a chat app using Node as a server, working perhaps on a different port on the same machine.</p></blockquote>
<p>Typically this scenario can be simulated without Node, but as I said, with some disadvantages. Let&#8217;s say you have two browsers and one server &#8211; you can infinitely loop AJAX calls to the server and whenever there is new message on the server return it to the browser &#8211; this is quite inefficient. There are two approaches in this case.</p>
<ol>
<li>You can make those AJAX calls too recently and you can have a call every N seconds. In that case if N is to short you&#8217;ll have too many calls and in case the other peer doesn&#8217;t make anything the server will be unusually loaded with no practical effect.</li>
<li>In the second case you can choose to make N too long &#8211; for instance 20 seconds. This is also bad, because during this period of time the peers may want to interact and chat.</li>
</ol>
<p>In that case Node is a web server, but simply doesn&#8217;t return the response until a specific event doesn&#8217;t occur. How does this look like in a web browser. You may know how looking into the <a title="Firebug" href="https://addons.mozilla.org/en-US/firefox/addon/1843/" target="_blank">Firebug console</a> for every AJAX call you see the request and how many seconds it has taken. If you make an AJAX call to a Node server app the request just doesn&#8217;t respond immediately.</p>
<h2>Installing Node.js</h2>
<p>The process of installation is <a title="Node.js Build" href="http://nodejs.org/#build" target="_blank">described quite well</a>, so I&#8217;m going to describe it in few steps.</p>
<ol>
<li>Download the application from Git, note that V8 is embedded inside. The version while this post was written and of course was stable is <a title="Node.js v0.2.4" href="http://nodejs.org/dist/node-v0.2.4.tar.gz" target="_blank">v0.2.4</a></li>
<li>For those familiar with Unix/Linux systems, there are three simple steps following, however without <a title="Gnu Compiler Collection" href="http://gcc.gnu.org/" target="_blank">GCC (Gnu Compiler Collection)</a> you wont be able to proceed! I&#8217;m writing this especially for the Mac OS users, as they may know there is no built-in GCC there.</li>
<li>./configure</li>
<li>make</li>
<li>make install</li>
<li>make test (optional)</li>
</ol>
<p>This in general is enough. After all that you can write the node command in your terminal. However if there are some problems while compiling it you may refer to Git and the Node community for more help. Don&#8217;t forget that V8 can work only on x86, x64 and ARM architectures.</p>
<h2>Summary</h2>
<p>There are few things that can be summarized now:</p>
<ol>
<li>First of all Node can be a web server, as Apache is, but with the option to respond on event firing.</li>
<li>You can request it either with a web page loaded in your browser or within a chunk of the page via AJAX.</li>
<li>To install Node you need GCC. It comes with V8 JavaScript engine inside, which can run only on x86, x64 and ARM.</li>
</ol>
<p>So far so good! Now we have Node installed, practically useless, because there is no application running on it. In my next post I&#8217;ll describe how to run your first application.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/12/02/diving-into-node-js-a-long-polling-example/" rel="bookmark" title="Diving into Node.js &#8211; A Long Polling Example">Diving into Node.js &#8211; A Long Polling Example </a></li>
<li><a href="/2010/11/19/diving-into-node-js-very-first-app/" rel="bookmark" title="Diving into Node.js &#8211; Very First App">Diving into Node.js &#8211; Very First App </a></li>
<li><a href="/2010/01/31/speed-up-the-javascript-it-can-change-dramatically-the-user-experience/" rel="bookmark" title="Speed up the JavaScript. It can change dramatically the user experience.">Speed up the JavaScript. It can change dramatically the user experience. </a></li>
<li><a href="/2010/01/11/what-should-be-optimized-in-one-web-page/" rel="bookmark" title="What should be optimized in one web page?">What should be optimized in one web page? </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/11/16/diving-into-node-js-introduction-and-installation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>2xjQuery: Select a Selector</title>
		<link>/2010/09/24/2xjquery-select-a-selector/</link>
		<comments>/2010/09/24/2xjquery-select-a-selector/#comments</comments>
		<pubDate>Fri, 24 Sep 2010 08:23:58 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Comparison of JavaScript frameworks]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Ext]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery javascript library]]></category>
		<category><![CDATA[jquery selectors]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[openlayers]]></category>
		<category><![CDATA[openlayers library]]></category>
		<category><![CDATA[Span and div]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[World Wide Web]]></category>

		<guid isPermaLink="false">/?p=1989</guid>
		<description><![CDATA[Selectors in jQuery If you&#8217;re familiar with jQuery you should already know what are selectors and how they work. However we&#8217;re used to get some DOM element with a specific selector, but actually sometimes you cannot select directly what you need. This is especially true when mixing more than one JavaScript libraries. In my case &#8230; <a href="/2010/09/24/2xjquery-select-a-selector/" class="more-link">Continue reading <span class="screen-reader-text">2xjQuery: Select a Selector</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/01/08/jquery-vs-pure-javascript/" rel="bookmark" title="jQuery vs. pure JavaScript">jQuery vs. pure JavaScript </a></li>
<li><a href="/2009/07/29/cancel-bubbling-on-element-click-with-jquery/" rel="bookmark" title="cancel bubbling on element click with jQuery">cancel bubbling on element click with jQuery </a></li>
<li><a href="/2009/11/02/ajax-in-jquery/" rel="bookmark" title="$.ajax in jQuery">$.ajax in jQuery </a></li>
<li><a href="/2009/04/01/jquery-accessing-a-child-element/" rel="bookmark" title="jQuery &#8211; accessing a child element">jQuery &#8211; accessing a child element </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Selectors in jQuery</h2>
<p><a href="/wp-content/uploads/2010/09/jquery.png"><img class="alignleft size-full wp-image-1999" title="jquery" src="/wp-content/uploads/2010/09/jquery.png" alt="jQuery JavaScript Library" width="259" height="65" /></a></p>
<p>If you&#8217;re familiar with <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a> you should already know what are selectors and how they work. However we&#8217;re used to get some DOM element with a specific selector, but actually sometimes you cannot select directly what you need. This is especially true when mixing more than one JavaScript libraries. In my case <a title="OpenLayers" href="http://openlayers.org/" target="_blank">OpenLayers</a> generated a vector layer and jQuery was supposed to change the vectors fill-color property.</p>
<p><a href="/wp-content/uploads/2010/09/openlayers.png"><img class="alignleft size-full wp-image-2000" title="openlayers" src="/wp-content/uploads/2010/09/openlayers.png" alt="OpenLayers" width="195" height="37" /></a></p>
<p>With the simple $(&#8216;path&#8217;) I easily got all vectors in the current document, but the problem was that I took them as text. Thus it came to me to use nested jQuery &#8211; $($(&#8216;selector&#8217;));</p>
<p>To describe what actually happened in my case, let me show you a breve example.</p>
<h2>Example</h2>
<p>Here&#8217;s a short HTML markup:</p>
<pre lang="html4strict">
<div><span>text text</span></div>

</pre>
<p>With jQuery I can select both the DIV and SPAN with the simple $(&#8216;div&#8217;) and $(&#8216;span&#8217;), but just for the example lets assume I&#8217;ve only the inner text of the DIV tag:</p>
<pre lang="javascript">$('div').html();
</pre>
<p>That was the case in the OpenLayers/jQuery problem. Now I can easily use another jQuery selector:</p>
<pre lang="javascript">$($('div').html());
</pre>
<p>This will return the same as $(&#8216;span&#8217;) &#8211; a jQuery object.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/01/08/jquery-vs-pure-javascript/" rel="bookmark" title="jQuery vs. pure JavaScript">jQuery vs. pure JavaScript </a></li>
<li><a href="/2009/07/29/cancel-bubbling-on-element-click-with-jquery/" rel="bookmark" title="cancel bubbling on element click with jQuery">cancel bubbling on element click with jQuery </a></li>
<li><a href="/2009/11/02/ajax-in-jquery/" rel="bookmark" title="$.ajax in jQuery">$.ajax in jQuery </a></li>
<li><a href="/2009/04/01/jquery-accessing-a-child-element/" rel="bookmark" title="jQuery &#8211; accessing a child element">jQuery &#8211; accessing a child element </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/09/24/2xjquery-select-a-selector/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Looping Animation with JavaScript and Raphaël</title>
		<link>/2010/09/13/looping-animation-with-javascript-and-raphael/</link>
		<comments>/2010/09/13/looping-animation-with-javascript-and-raphael/#respond</comments>
		<pubDate>Mon, 13 Sep 2010 13:40:50 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Graphics file formats]]></category>
		<category><![CDATA[JavaScript library]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[Raphael]]></category>
		<category><![CDATA[Scalable Vector Graphics]]></category>
		<category><![CDATA[Vector graphics markup languages]]></category>
		<category><![CDATA[Vector Markup Language]]></category>

		<guid isPermaLink="false">/?p=1980</guid>
		<description><![CDATA[Raphael is a popular JavaScript library helping you to manage vectors via SVG or VML in your browser. It is extremely helpful and very easy to learn and use. The interesting thing is that in the browser you can do very powerful things with vectors, but they remain very less known. However with such libraries &#8230; <a href="/2010/09/13/looping-animation-with-javascript-and-raphael/" class="more-link">Continue reading <span class="screen-reader-text">Looping Animation with JavaScript and Raphaël</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/14/javascript-array-pop-get-the-last-item/" rel="bookmark" title="JavaScript array.pop() &#8211; Get The Last Item">JavaScript array.pop() &#8211; Get The Last Item </a></li>
<li><a href="/2010/09/27/jquery-setting-up-a-vector-path-fill-color/" rel="bookmark" title="jQuery: Setting Up a Vector Path Fill Color">jQuery: Setting Up a Vector Path Fill Color </a></li>
<li><a href="/2010/09/24/2xjquery-select-a-selector/" rel="bookmark" title="2xjQuery: Select a Selector">2xjQuery: Select a Selector </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><a title="Raphael.js" href="http://raphaeljs.com/index.html" target="_blank">Raphael</a> is a popular JavaScript library helping you to manage vectors via SVG or VML in your browser. It is extremely helpful and very easy to learn and use. The interesting thing is that in the browser you can do very powerful things with vectors, but they remain very less known. However with such libraries like Raphael the task is really simple.</p>
<h2>Animation</h2>
<p>As I said animating some vector properties is as simple as:</p>
<pre lang="javascript">var paper = Raphael('canvas', 1024, 500);
var c = paper.circle(50, 50, 6).attr({fill : '#f00'});
c.animate({r : 10, fill : '#00f'}, 1000);
</pre>
<p>Here we change the radius and the background color of the circle for 1000 milliseconds.</p>
<p>The same thing can be done with any property with any other JavaScript library as <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>. But as in jQuery, Raphael or whatever library the animation is not looping. That&#8217;s natural you can just change a property by animating it, but the looping animation suggests at least two animations. So it&#8217;s a developers job to implement this. Here&#8217;s a simple way to do this.</p>
<h2>Two Way Animation</h2>
<p>The solution here is using two functions calling each other.</p>
<pre lang="javascript">
var paper = Raphael('canvas', 1024, 500);
var c = paper.circle(50, 50, 6).attr({fill : '#f00'});

function a() {
    c.animate({r : 10, fill : '#00f'}, 1000, b);
}
function b() {
    c.animate({r : 6, fill : '#f00'}, 1000, a);
}
a();
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/14/javascript-array-pop-get-the-last-item/" rel="bookmark" title="JavaScript array.pop() &#8211; Get The Last Item">JavaScript array.pop() &#8211; Get The Last Item </a></li>
<li><a href="/2010/09/27/jquery-setting-up-a-vector-path-fill-color/" rel="bookmark" title="jQuery: Setting Up a Vector Path Fill Color">jQuery: Setting Up a Vector Path Fill Color </a></li>
<li><a href="/2010/09/24/2xjquery-select-a-selector/" rel="bookmark" title="2xjQuery: Select a Selector">2xjQuery: Select a Selector </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/09/13/looping-animation-with-javascript-and-raphael/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Returning JSON in a Zend Controller’s Action &#8211; Part 2</title>
		<link>/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/</link>
		<comments>/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 13:39:23 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[elegant solution]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[JSON-RPC]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[Remote procedure call]]></category>
		<category><![CDATA[SOAPjr]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Web services]]></category>

		<guid isPermaLink="false">/?p=1916</guid>
		<description><![CDATA[In a reply from my latest post after following the comments, there is a much elegant solution to this use case. Simply by changing the output with a JSON helper. This also changes the content-type of the returned response. $data = array(...); $this->_helper->json($data);<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/08/13/returning-json-in-a-zend-controllers-action/" rel="bookmark" title="Returning JSON in a Zend Controller&#8217;s Action">Returning JSON in a Zend Controller&#8217;s Action </a></li>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/06/23/bind-zend-action-with-non-default-view-part-2/" rel="bookmark" title="Bind Zend Action with Non-Default View &#8211; Part 2">Bind Zend Action with Non-Default View &#8211; Part 2 </a></li>
<li><a href="/2010/06/24/zend-framework-inject-javascript-code-in-a-actionview/" rel="bookmark" title="Zend Framework: Inject JavaScript Code in a Action/View">Zend Framework: Inject JavaScript Code in a Action/View </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>In a reply from my latest post after following the comments, there is a much elegant solution to this use case. Simply by changing the output with a JSON helper. This also changes the content-type of the returned response.</p>
<pre lang="php">
$data = array(...);
$this->_helper->json($data);
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/08/13/returning-json-in-a-zend-controllers-action/" rel="bookmark" title="Returning JSON in a Zend Controller&#8217;s Action">Returning JSON in a Zend Controller&#8217;s Action </a></li>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/06/23/bind-zend-action-with-non-default-view-part-2/" rel="bookmark" title="Bind Zend Action with Non-Default View &#8211; Part 2">Bind Zend Action with Non-Default View &#8211; Part 2 </a></li>
<li><a href="/2010/06/24/zend-framework-inject-javascript-code-in-a-actionview/" rel="bookmark" title="Zend Framework: Inject JavaScript Code in a Action/View">Zend Framework: Inject JavaScript Code in a Action/View </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Returning JSON in a Zend Controller&#8217;s Action</title>
		<link>/2010/08/13/returning-json-in-a-zend-controllers-action/</link>
		<comments>/2010/08/13/returning-json-in-a-zend-controllers-action/#comments</comments>
		<pubDate>Fri, 13 Aug 2010 13:14:26 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[clear solution]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[encode()]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[JSON-RPC]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[zend_json]]></category>

		<guid isPermaLink="false">/?p=1905</guid>
		<description><![CDATA[There are three basic ways that you can achieve that. First of all what&#8217;s the task? You&#8217;ve an array, either from a database result or whatever, and you encode it JSON with Zend_Json::encode($array) // IndexController.php class IndexController extends Zend_Controller_Action { public function indexAction() { $data = array(...); $this->view->data = Zend_Json::encode($data); } } The result in &#8230; <a href="/2010/08/13/returning-json-in-a-zend-controllers-action/" class="more-link">Continue reading <span class="screen-reader-text">Returning JSON in a Zend Controller&#8217;s Action</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/" rel="bookmark" title="Returning JSON in a Zend Controller’s Action &#8211; Part 2">Returning JSON in a Zend Controller’s Action &#8211; Part 2 </a></li>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/06/07/bind-zend-action-with-non-default-view/" rel="bookmark" title="Bind Zend Action with Non-Default View">Bind Zend Action with Non-Default View </a></li>
<li><a href="/2010/06/24/zend-framework-inject-javascript-code-in-a-actionview/" rel="bookmark" title="Zend Framework: Inject JavaScript Code in a Action/View">Zend Framework: Inject JavaScript Code in a Action/View </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>There are three basic ways that you can achieve that. First of all what&#8217;s the task? You&#8217;ve an array, either from a database result or whatever, and you encode it JSON with Zend_Json::encode($array)</p>
<pre lang="php">
// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
		
		$this->view->data = Zend_Json::encode($data);	
	}	
}
</pre>
<p>The result in general is a specially formatted string. So you can simply set it up to a view member variable and pass it to the view.</p>
<pre lang="php">
// index/index.phtml
echo $this->data
</pre>
<p>In that case you&#8217;ve a .phtml file to maintain, so lets just return the string and &#8220;setNoRender&#8221; the view in our second try.</p>
<pre lang="php">
// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
		
		echo Zend_Json::encode($data);	
		
		$this->_helper->viewRenderer->setNoRender(true);
	}	
}
</pre>
<p>Actually this is pretty much the most clear solution, but actually you can output the JSON string and simply exit() as it&#8217;s shown in our third example.</p>
<pre lang="php">
// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
		
		echo Zend_Json::encode($data);	
		
		exit();
	}	
}
</pre>
<p>Which one is to be used is up to the developer&#8217;s choice, mine is the third one as it&#8217;s the minimal one.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/" rel="bookmark" title="Returning JSON in a Zend Controller’s Action &#8211; Part 2">Returning JSON in a Zend Controller’s Action &#8211; Part 2 </a></li>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/06/07/bind-zend-action-with-non-default-view/" rel="bookmark" title="Bind Zend Action with Non-Default View">Bind Zend Action with Non-Default View </a></li>
<li><a href="/2010/06/24/zend-framework-inject-javascript-code-in-a-actionview/" rel="bookmark" title="Zend Framework: Inject JavaScript Code in a Action/View">Zend Framework: Inject JavaScript Code in a Action/View </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/08/13/returning-json-in-a-zend-controllers-action/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
