<?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>Scott Nelle.com &#187; Javascript</title>
	<atom:link href="http://www.scottnelle.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.scottnelle.com</link>
	<description>Scott Nell&#233;&#039;s Personal Site</description>
	<lastBuildDate>Thu, 03 Jun 2010 15:46:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Introduction to Ajax with Mootools</title>
		<link>http://www.scottnelle.com/20/introduction-to-mootools-ajax-tutorial/</link>
		<comments>http://www.scottnelle.com/20/introduction-to-mootools-ajax-tutorial/#comments</comments>
		<pubDate>Sun, 23 Dec 2007 22:05:51 +0000</pubDate>
		<dc:creator>Scott Nelle</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.scottnelle.com/20/introduction-to-mootools-ajax-tutorial/</guid>
		<description><![CDATA[This is a basic tutorial that offers an introduction to the Ajax component of the mootools javascript library. At the end of this tutorial youâ€™ll be able to use an HTML form to send requests to a PHP script and return a response without refreshing the page. This basic process is the foundation for most [...]]]></description>
			<content:encoded><![CDATA[<p>This is a basic tutorial that offers an introduction to the Ajax component of the <a href="http://www.mootools.net/">mootools javascript library</a>.  At the end of this tutorial youâ€™ll be able to use an HTML form to send requests to a PHP script and return a response without refreshing the page.  This basic process is the foundation for most of the ajax that you see littered around the internet today.  Mootools offers a simple way to get your feet wet with this technology, and plenty of room to grow once you know what youâ€™re doing.</p>
<p>This tutorial is something of a followup to one that I wrote some time ago, describing the same basic process using the moo.ajax class, a precursor to mootools.  That article still gets a fair number of visits on my site, but since moo.ajax has been deprecated it isnâ€™t very useful.  This tutorial expands on that one a little, but is essentially an update.  By now everyone has heard of ajax, so thereâ€™s no need to repeat the introduction.  Letâ€™s get started.</p>
<h3>What Youâ€™ll Need</h3>
<ul>
<li><strong>Some way to run PHP scripts.</strong>  Many web hosts offer this.  You can also set up a web server on your personal computer, which will make the development process much more simple.</li>
<li><strong>A copy of the mootools library.</strong>  I&#8217;ll show you how to get a customized version that meets all of our requirements.</li>
</ul>
<h3>Downloading mootools</h3>
<p>Go to the <a href="http://www.mootools.net/download">mootools download page</a> to grab the required files.  The core component will already be selected.  Find the Ajax component under the Remote section and select that.  It will automatically select a handful of other components that mootools needs to run the Ajax component. Iâ€™ve also checked Window.DomReady, which selects the event component and will allow us to add Ajax to a form unobtrusively (that is, without making a mess of the HTML.) Click on Choose Compression to select the preferred level of compression for your customized mootools library, which you can then download.  I chose no compression because Iâ€™m creating a tutorial.  You can choose whatever suits you.  For live sites Iâ€™d recommend using the JavaScript Packer compression to decrease file size (from 90KB to 20KB in this case.)  I&#8217;ve included the uncompressed version along with the example files. You can develop with the uncompressed version and then switch in the packed version when you make the code live.  You wonâ€™t have to change any of your code to take advantage of the reduced file size.</p>
<p>You can follow along with this tutorial by either viewing source on the example page or downloading the full source below.</p>
<ul>
<li><a href="/tutorials/mootools/ajax/example/">View the example</a></li>
<li><a href="/tutorials/mootools/ajax/mootools1.zip" title="Download source files for this example (27kb zip file)">Download the source</a></li>
</ul>
<h3>The Example</h3>
<p><a href="/tutorials/mootools/ajax/example/">The example</a> is a super-simple application that accepts two numbers.  When you submit the form it will send the values to a PHP script via ajax, multiply them on the server, and return them to the page without refreshing.  It will show this value in two places; mootools has the ability to update the contents of an element with your PHP script response or define a custom function to handle the returned data; I&#8217;ve chosen to show both. If javascript has been disabled it will simply print the return value out on an unstyled page.  Not everyone is browsing with javascript enabled, so it&#8217;s important to ensure that they can still use your application without it.  I could have done much more to make the non-javascript version nicer to use, but for now it performs its basic function and that&#8217;s a good start.</p>
<h3>How it works</h3>
<p>If you&#8217;ve looked at the source, you&#8217;ll see a pretty standard HTML page.  It has a head section that includes a stylesheet, the mootools javascript file, and the application logic.  It also has a body with a form in it.  The application logic is the part where the cool stuff happens.  Unlike my previous tutorial, I&#8217;ve taken advantage of some cool aspects of mootools to make this code clean and compact.  I&#8217;ll explain these lines along the way.</p>
<pre><code>
window.addEvent('domready', function(){
	&hellip;
});
</code></pre>
<p>This block wraps around the rest of our code and tells the script to run once the DOM has loaded.  That means it will run as soon as the document has been read into memory (but before all the images have loaded.)  This avoids the delay you get with most javascript solutions.  Inside this block, you&#8217;ll see another block:</p>
<pre><code>
$('testform').addEvent('submit', function(e){
	// stop the default form submit event
	new Event(e).stop();
	&hellip;
});
</code></pre>
<p>This tells the form &#8220;When the user submits testform, don&#8217;t perform your normal form action.&#8221;  <code>$('testform')</code> tells mootools that you&#8217;re adding the code to an element with an id of testform (our simple form, as it happens.)  Inside this block, we&#8217;re going to add instructions for what should happen instead.</p>
<pre><code>
var postString = "value1=" + $('value1').value + "&#038;value2=" + $('value2').value;
</code></pre>
<p>Here we&#8217;re creating a string of data to post to the PHP script.  This grabs the data from our form and creates a string like <code>value1=5&#038;value2=6</code>.  This step isn&#8217;t strictly necessary, but the values  will be passed as an option to the ajax request next, and I wanted to keep that request looking pretty clean.  </p>
<pre><code>
var myAjax = new Ajax('data.php', {
	method: 'post',
	data: postString,
	update: $('output1'),
	onComplete: function(req){
		$('output2').innerHTML = req;
		$('output2').style.background = "#adf";
	}
}).request();
</code></pre>
<p>This is the last bit of the script. It creates a new <code>Ajax</code> object called <code>myAjax</code> and sets the URL for the file you want to submit to, assigning some options to the request.  The first is a like a form method.  Just like any html form, you can submit the data using <code>post</code> and <code>get</code>.  If you don&#8217;t specify anything, it defaults to <code>post</code>.  Next we pass the request data as a string.  Here, I&#8217;ve used the variable that we set earlier.  Next, we use the update option to specify the id of an element.  Mootools will automatically update the content of that element with whatever the PHP script sends back.  Finally, the onComplete option allows you to specify a function to run when the ajax request is complete.  Here I&#8217;ve told it to update another element with the same information and to highlight that element, just to show that it&#8217;s actually my function and not the update option at work.  Now that we&#8217;re done setting up the new <code>Ajax</code> object, we call it&#8217;s <code>request</code> method to automatically make the request.</p>
<p>So that&#8217;s it.  Your first steps into the world of ajax.  I&#8217;ve included the whole script below so you can see how short it really is.  In case you missed it above, you can <a href="/tutorials/mootools/ajax/example/">view the example</a> and <a href="/tutorials/mootools/ajax/mootools1.zip">download the full source</a>.</p>
<pre><code>
&lt;script type="text/javascript"&gt;
//&lt;![CDATA[
// this is our javascript application logic

	// This happens once the DOM has loaded.
	window.addEvent('domready', function(){
		$('testform').addEvent('submit', function(e){
			// stop the default form submit event
			new Event(e).stop();

			// create a string of the variables we want to post to the php script
			// this will look like like "value1=5&#038;value2=6"
			var postString = "value1=" + $('value1').value + "&#038;value2=" + $('value2').value;

			// set some parameters for the ajax request...
			var myAjax = new Ajax('data.php', {
				method: 'post',
				data: postString,
				update: $('output1'),
				onComplete: function(req){
					$('output2').innerHTML = req;
					$('output2').style.background = "#adf";
				}
			}).request(); // ...and automatically make the ajax request
		});
	});
	//]]&gt;
&lt;/script&gt;
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.scottnelle.com/20/introduction-to-mootools-ajax-tutorial/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Introduction to Moo.Ajax</title>
		<link>http://www.scottnelle.com/8/introduction-to-moo-ajax/</link>
		<comments>http://www.scottnelle.com/8/introduction-to-moo-ajax/#comments</comments>
		<pubDate>Tue, 25 Jul 2006 14:46:46 +0000</pubDate>
		<dc:creator>Scott Nelle</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://www.scottnelle.com/8/introduction-to-moo-ajax/</guid>
		<description><![CDATA[Update: Moo.Ajax has become deprecated since I originally wrote this article, as its functionality has been incorporated into the new mootools library. I&#8217;ve written a follow-up piece that explains this same basic principal using the more current library. I&#8217;d suggest checking that out if you&#8217;re interested in a dead-simple introduction to ajax. This is a [...]]]></description>
			<content:encoded><![CDATA[<p class="update"><strong>Update:</strong> Moo.Ajax has become deprecated since I originally wrote this article, as its functionality has been incorporated into the new mootools library.  <a href="/20/introduction-to-mootools-ajax-tutorial/">I&#8217;ve written a follow-up piece</a> that explains this same basic principal using the more current library.  I&#8217;d suggest checking that out if you&#8217;re interested in a dead-simple introduction to ajax.</p>
<p>This is a very basic tutorial which offers a glance at the <a href="http://www.mad4milk.net/entry/moo.ajax" title="The main source for info about moo.ajax">moo.ajax</a> class from <a href="http://www.mad4milk.net/">Mad 4 Milk</a>. It doesn&#8217;t expand too much on the tutorial that they provide, but I feel that it will help clarify a few things.  Don&#8217;t let the length of this article frighten you, what you are about to learn is pretty simple.  I just use a lot of words to explain it.  By the time you&#8217;ve worked through this tutorial, you will be able to build a form that interacts with a PHP script and returns data, without refreshing the page.  It&#8217;s a pretty simple process that can serve as the basis for some very cool applications.</p>
<p>This tutorial should serve as an introduction to using moo.ajax for remote scripting.  If you are familiar with the technologies in use&mdash;XHTML, JavaScript, and PHP&mdash;you should be able to take these founding principals and run with them to create something interesting and perhaps even useful.  As a bonus, I&#8217;ve thrown in a bit about unobtrusive JavaScript and graceful degradation.  These are important principals in the new era of web scripting, and learning about them will help make you a rock star of web development and get you millions of dollars, or at least ensure that your applications are the best that they can be.</p>
<h3>Requirements</h3>
<p>To complete this tutorial you will need the following:</p>
<ul>
<li><strong>Some way to run PHP scripts.</strong>  Many web hosts offer this.  You can also set up a web server on your personal computer, which will make the development process much more simple.</li>
<li><strong>Prototype.lite.js</strong>.  This is a stripped down version of the <a href="http://prototype.conio.net/">Prototype JavaScript library</a>.  It is available from Mad 4 Milk, or in the example source file that I&#8217;ve included.</li>
<li><strong>moo.ajax.js</strong> This contains the ajax class that we will use.  Along with prototype.lite.js, it does most of the actual work.  It&#8217;s also available from Mad 4 Milk, or in the example source file that I&#8217;ve included.</li>
<li>That&#8217;s about it.</li>
</ul>
<p>I&#8217;ve packaged up the entire example, including the JavaScript files from Mad 4 Milk so that you can follow along at home.  You should be able to upload the files to your web host unmodified, and everything should work.  When we get to the code I&#8217;ll assume that you&#8217;ve downloaded it, or at least viewed the example and peeked at the source.</p>
<ul>
<li><a href="http://www.scottnelle.com/tutorials/mooajax/basic/example/">View the example</a></li>
<li><a href="http://www.scottnelle.com/tutorials/mooajax/basic/mooajax1.zip" title="Download source files for this example (4kb zip file)">Download the source</a></li>
</ul>
<h3>The Example&mdash;What&#8217;s Going On?</h3>
<p>Our example contains a form with one input.  When you submit the form, moo.ajax magically submits the input value to a PHP script, which does a little processing and then returns a value to the web page.  All this happens without refreshing the page, which is exciting to myself and probably to you as well.</p>
<p>This example expects that you input a number.  If you don&#8217;t do so, it politely asks you to try again.  That&#8217;s about all you need to know to use it, so without further delay I&#8217;ll teach you how to build it.</p>
<h3>Getting Started</h3>
<p>At the heart of this whole thing is a simple html page with a simple form on it.  I&#8217;ll assume you know how (or can figure out how) to tackle that portion of it.  If not, you can see mine in the source code.    Moving on, we add the follwing to the head of the document:</p>
<pre><code>
&lt;script type="text/javascript" src="prototype.lite.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="moo.ajax.js"&gt;&lt;/script&gt;
</code></pre>
<p>Here we&#8217;ve include the scripts that perform the magic.  You can look at their contents in your free time.  For now, we&#8217;ll just include them and hope that they work (don&#8217;t worry, they do.)</p>
<h3>Get To The Cool Stuff Already!</h3>
<p>OK, get ready.  The next code snippet is where we do our thing, which is to tell moo.ajax to do it&#8217;s thing.  Check this action out:</p>
<pre><code>
function letsRock()
{
	var postString = "thevalue=" + document.getElementById("thevalue").value;
	new ajax('data.php', {postBody: postString, update: 'output1', onComplete: itsOver});
}

function itsOver(request)
{
	document.getElementById("output2").innerHTML = request.responseText;
}
</code></pre>
<p>Well that was anti-climactic.  Something as cool as ajax should require impossibly complicated scripts that make your friends jealous, right?  Perhaps it <em> should</em>, but fortunately for us, it doesn&#8217;t.  The cool folks at Mad 4 Milk have made our work easy by providing their tools.  So what&#8217;s exactly is going on in this little snippet of code?</p>
<p>First, there&#8217;s the function <code>letsRock()</code>.  This gets called when you submit the form.  The first line of the function declares a variable <code>postString</code> and builds a string to be passed to the PHP script.  If you entered 3 in the input field, the variable would store &#8220;<code>thevalue=3</code>&#8220;.  This string can store multiple fields; use <code>&amp;</code> to separate them.</p>
<p>The second line of our function creates a new <code>ajax</code> object (defined in moo.ajax.js.)  The first parameter is the URL of the script we want to access through ajax (you&#8217;ll get a look at that script in a moment.)  Next comes a list of options.  <code>postBody</code> tells the ajax gods that we want to pass data to our PHP script using the post method (vs. get, just like with a regular form.)  postString is the variable we defined on the previous line.  Building a string variable might have been overkill here, but if we decide to pass a lot of data to the script it could become quite messy.  Using a variable helps us keep the script clean-looking.</p>
<p>The next option calls the <code>update</code> method, which comes from moo.ajax.js.  Specify the an DOM object or the id of an element and the <code>update</code> method (optional) takes the output of your PHP script and dumps it into that element rather than outputting to a new page as is typically would.  In this case the output goes to one of two paragraphs just below the form.</p>
<p>Finally, the <code>onComplete</code> method (also from moo.ajax.js, also optional) runs a function of our choosing when the request is complete.  I&#8217;ve chosen to run a function called <code>itsOver</code>, which just duplicates what already happened with the <code>update</code> method.  I just did this to demonstrate two different ways of handling output.  <code>update</code> is a simple, prebuilt way to display the results of our script call, and <code>onComplete</code> offers an infinitely flexible way to handle the next step once a request has been completed.  Pick whichever one suits your needs best when building your own scripts.</p>
<p>Lets just take a quick peek at <code>itsOver</code>, since we already know what it&#8217;s doing.  When the request is complete, the function is fired.  The output element of choice is filled with the <code>responseText</code> (once again, provided by moo.ajax.js) which is the regular screen output of our PHP script.  InnerHTML is a pretty good way to display this text, but not the best.</p>
<h3>What about that PHP script?  Let&#8217;s See That.</h3>
<p>The PHP script in this example is very simple.  All it does is take the value that you enter and multiply it by another number, to prove that it&#8217;s interacting with the server.  Any PHP script can be used with the ajax call that we&#8217;ve made.  In our case, we have 1 piece of post data to handle, and we&#8217;d like to return some output to display on the example page.  Here&#8217;s the PHP script in its entirety:</p>
<pre><code>
&lt;?
$multiplier = 4;
if ($result = $multiplier * $_POST['thevalue'])
	print "The result is " . $result . ". The multiplier that we used was " . $multiplier;
else
	print "Please enter a number";
?&gt;
</code></pre>
<p>The first line sets a multiplier variable, which will be multiplied by the number that is submitted to the script.  The next line is a simple if statement that multiplies the submitted value by the multiplier.  If the value is a number, the calculation will be performed successfully and it will return true.  Otherwise, the calculation will fail and return false.  Again, I&#8217;d like to mention that this is a very basic script used only for demonstrative purposes.  The sky is really the limit as far as what you can do here.  We&#8217;re passing post values just like any normal form, so you can do anything here that you would in a normal PHP application.</p>
<h3>Executing The Ajax Call</h3>
<p>Next, we have a bit of scripting to add this functionality to our form.  If you&#8217;re already familiar with the concepts of unobtrusive JavaScript, <code>addEvent</code>, and graceful degradation, you can just skip the rest of this tutorial, smarty-pants.  The rest of you, have a peek at the rest of the JavaScript:</p>
<pre><code>
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}
function initializer() {
var testForm = document.getElementById('testform');
	addEvent(testForm, 'submit', letsRock);
	testForm.onsubmit = function() { return false; }
}
addEvent(window, 'load',initializer);
&lt;/script&gt;
</code></pre>
<p>The <code>addEvent</code> function is a pretty common one, that has been written in many different ways.  Basically, it adds an event listener (e.g. <code>onclick</code> or <code>onmouseover</code>) to an html object.  The version that I&#8217;m using was grabbed from this post at quirksmode.org.  For now, just include it in the file.  In the future, you might want to put it in a separate file with other common functions, because you&#8217;ll want to use it constantly.  &quot;Why not just add and onclick to the form code?&quot; you might ask.  The short answer is that it keeps your code clean and easy to maintain&#8211;it&#8217;s called unobtrusive JavaScript, and it&#8217;s the right way to do it.  A longer answer can be found via the <a href="http://domscripting.webstandards.org/?page_id=2">DOM Scripting Task Force</a>.</p>
<p>After our addEvent function, we have a function called <code>initializer</code>.  This uncreatively named function prepares the form to do it&#8217;s ajaxy thing.  First, we declare a variable and store a reference to our form, for ease of use in the next two lines.  Then we use <code>addEvent</code> to make the form to execute our <code>letsRock</code> function (defined above) when it is submitted.  Then, we tell the form to return false when it is submitted.  This prevents the form from bringing us directly to the PHP page when it the user presses &quot;Submit&quot;, and instead allows <code>letsRock</code> to do it&#8217;s work.</p>
<p>Finally, we use another addEvent to attach our initializer function to the onload event handler for the web browser window.  This means that once the window loads, and all the elements have been created, the other events will be attached.  This prevents errors that can be caused by trying to modify a page element before it is created.</p>
<p>An interesting thing to note about all this JavaScript is that the form will work without it.  Don&#8217;t believe me?  Go ahead and try it with JavaScript turned off.  The output isn&#8217;t as pretty, but you get the same information.  This is what&#8217;s meant by &#8220;graceful degredation&#8221;&#8211;whenever possible, you should write applications that will work without JavaScript.  This allows your application to be functional to the greatest number of users.</p>
<h3>What&#8217;s Left?</h3>
<p>Not much.  All we have to do is build the HTML page.  The tricky stuff is over.  The rest of the code is available in the file download or the example source, so I won&#8217;t bother repeating it here.</p>
<p>In case you missed it before, <a href="http://www.scottnelle.com/tutorials/mooajax/basic/example/">here&#8217;s the example</a> again.</p>
<h3>Debriefing</h3>
<p>I&#8217;d just like to state once more that this is pretty much the ground floor of using ajax.  There are better and more complicated ways of doing most of what I&#8217;ve done here, and there is no upper limit to the impressive things that you can achieve with the technology and a bit of creativity.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.scottnelle.com/8/introduction-to-moo-ajax/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>
