<?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>edrackham &#187; JavaScript</title>
	<atom:link href="http://edrackham.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://edrackham.com</link>
	<description>PHP, MySQL, JavaScript and Other Web Tutorials!</description>
	<lastBuildDate>Tue, 21 Feb 2012 11:57:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>AJAX Form Tutorial</title>
		<link>http://edrackham.com/php/ajax-form-tutorial/</link>
		<comments>http://edrackham.com/php/ajax-form-tutorial/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 20:11:49 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[AJAX Form]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=149</guid>
		<description><![CDATA[This tutorial will show you how to create an AJAX form with PHP and jQuery. The AJAX form doesn&#8217;t look any different to an ordinary HTML form, with the exception of making sure that when we submit the form, it calls a javascript function rather than pushes the user to a page (causing a new [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial will show you how to create an AJAX form with PHP and jQuery. The AJAX form doesn&#8217;t look any different to an ordinary HTML form, with the exception of making sure that when we submit the form, it calls a javascript function rather than pushes the user to a page (causing a new page reload). I&#8217;ll also demonstrate how we can use &#8216;loading&#8217; animation for the AJAX form, whilst we wait for the server to respond.<span id="more-149"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2><a target="_blank" href="http://edrackham.com/tutorials/ajax-form-tutorial/">DEMO: HERE</a></h2>
<h2>The AJAX Form</h2>
<pre name="code" class="html">
&lt;form name=&quot;ajaxForm&quot; id=&quot;ajaxForm&quot; method=&quot;post&quot; action=&quot;&quot; onsubmit=&quot;postForm(); return false;&quot;&gt;
	&lt;label for=&quot;yourName&quot;&gt;Your Name&lt;/label&gt;
	&lt;input type=&quot;text&quot; name=&quot;yourName&quot; id=&quot;yourName&quot; /&gt;
	&lt;br /&gt;

	&lt;label for=&quot;yourAge&quot;&gt;Your Age&lt;/label&gt;
	&lt;input type=&quot;text&quot; name=&quot;yourAge&quot; id=&quot;yourAge&quot; /&gt;

	&lt;br /&gt;

	&lt;label for=&quot;submitForm&quot;&gt;&amp;nbsp;&lt;/label&gt;
	&lt;input type=&quot;submit&quot; id=&quot;submitForm&quot; value=&quot;Submit&quot; /&gt;

	&lt;input type=&quot;hidden&quot; name=&quot;formPosted&quot; value=&quot;true&quot; /&gt;
&lt;/form&gt;
</pre>
<p>We&#8217;re using a simple form for this tutorial, but feel free to add any number of form elements you wish. In this example, we have given the form an id of <strong>ajaxForm</strong>, we also have a field for <strong>yourName</strong> and a field for <strong>yourAge</strong>. As explained in my <a href="http://edrackham.com/php/php-login-script-tutorial/">User Login Script</a> tutorial, we also have a hidden field that I like to use to confirm that the page was actually submitted, and which form was the &#8220;sender&#8221;. The most important thing about this form, and to make it work using AJAX, is the following attribute within our opening form tag:</p>
<pre name="code" class="html">
onsubmit=&quot;postForm(); return false;&quot;
</pre>
<p>The <strong>onsubmit</strong> attribute allows us to execute some JavaScript (to eventually run our AJAX!) prior to actually sending the form using it&#8217;s default method (by sending the form data to the page via a complete page reload). We&#8217;re immediately calling <strong>return false;</strong> straight after, this actually prevents the form from sending the data the normal way.</p>
<p>If it helps to understand, here&#8217;s all we&#8217;ve done up to this point:</p>
<ul>
<li>Create a simple HTML form</li>
<li>Add the <strong>onsubmit</strong> attribute to the opening form tag</li>
<li>Made a call to a (currently non-existent) JavaScript function within the <strong>onsubmit</strong> attribute</li>
<li>Returned false after our call to the JavaScript function &#8211; to prevent the form from actually submitting</li>
</ul>
<h2>The AJAX Preloader</h2>
<p>Our form is all dealt with, so now let&#8217;s create a little div, which will show when our form is sending the data, and waiting for some response back. After your form, add the following:</p>
<pre name="code" class="html">
&lt;div id=&quot;loading&quot; style=&quot;display: none;&quot;&gt;
	&lt;img src=&quot;loader.gif&quot; style=&quot;vertical-align: middle;&quot; /&gt; Loading...
&lt;/div&gt;
</pre>
<p>This is a real simple little div, which is hidden by default (using the <strong>style=&#8221;display: none&#8221;</strong> attribute). We&#8217;ve given it an id of <strong>loading</strong>, which is important as we&#8217;ll need to use the jQuery to show / hide this div in a moment. Inside this div I have placed a preloading gif which I created using <a href="http://www.preloaders.net/">http://www.preloaders.net</a>, and a simple bit of text saying &#8216;Loading&#8230;&#8217;. You can put whatever you like within this div really, but I quite like the preloading animated gifs myself.</p>
<h2>The Actual AJAX Function</h2>
<p>Ok, so we&#8217;re diverting the actual onsubmit action of the form to a JavaScript function called <strong>postForm()</strong>. We&#8217;re using jQuery to handle this AJAX form as it&#8217;s a much easier method than manually writing a cross-browser XMLHttpRequest handler. I&#8217;m assuming you know how to include jQuery into your page, but if not &#8211; take a quick peek at my <a href="http://edrackham.com/javascript/how-to-create-a-textarea-character-counter-limiter-using-jquery/">Textarea Counter</a> tutorial, which explains my preferred method for including jQuery libraries.</p>
<p>Right, you have jQuery included? Good, let&#8217;s go and create the <strong>postForm()</strong> function now. It looks like the following:</p>
<pre name="code" class="javascript">
function postForm(){
	$('#loading').show('fast');
	$.post("index.php", $("#ajaxForm").serialize(),
	   function(data){
			$('#loading').hide('fast');
	     alert("Your name is: " + data.name + "\nYour age is: " + data.age);
	   }, "json");
}
</pre>
<p>The first thing we&#8217;re doing is showing the loading div (with our preloader). We do this by calling:</p>
<pre name="code" class="javascript">
$('#loading').show('fast');
</pre>
<p>This does a quick fade-in of our loading div, before we do anything else. This is a good idea, because we want to give the user immediate feedback that something it happening. We could also disable the submit button at this point &#8211; but that&#8217;s not covered in the scope of this tutorial.</p>
<p>Next comes our actual AJAX call which will submit our form. I&#8217;m using $.post() in this tutorial, but you can use $.get() and even $.getJSON().</p>
<ul>
<li>$.post() will simulate a form POST (as if we had our form method set to post)</li>
<li>$.get() will simulate a form GET request (as if we had our form method set to get)</li>
<li>$.getJSON will simulate a GET request as above, but expect the results to be well formatted JSON, and as such return it as JSON data</li>
</ul>
<p>A quick look at the jQuery docs for how the $.post() function should be formatted shows that we can use numerous methods, but for this tutorial we want to set <strong>four main things</strong>.</p>
<p>The page we&#8217;re submitting the form data to. As explained in my <a href="http://edrackham.com/php/php-login-script-tutorial/">User Login Script</a> tutorial, I like to submit the data to the same page, so this is going to be set to <strong>index.php</strong> (and we&#8217;ll get to how we handle the data in a moment!).</p>
<p>Next, we need to tell the AJAX call what data we&#8217;re going to be sending. As we&#8217;re using a well-formatted form (when using AJAX, you won&#8217;t always necessarily be using a form), we&#8217;re going to use a great jQuery function called serialize() which &#8211; in basic terms &#8211; tells our function that we&#8217;re sending all elements within the form that we&#8217;re serializing. We do this by calling <strong>$(&#8220;#ajaxForm&#8221;).serialize()</strong> (essentially, we&#8217;re serializing all the data within the <strong>ajaxForm</strong> &#8211; remember, this is the ID of the form we created earlier).</p>
<p>After that comes our &#8220;success&#8221; function. In other words, a function that gets automatically called once our AJAX call has had a response from the page that we&#8217;re sending the data to. This is taking an automatic parameter which I&#8217;ve called <strong>data</strong>. You can name this parameter anything you like (provided it&#8217;s not a <a href="https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words">reserved JavaScript word</a>), but generally speaking &#8211; <strong>data</strong> is a good enough keyword, as essentially what we&#8217;ll be receiving is <strong>data</strong>.</p>
<p>We&#8217;ll break down that mini-function in a moment.</p>
<p>The fourth and final parameter that we need (for this tutorial anyway) is the &#8220;what data type are you expecting back?&#8221; parameter. I&#8217;ve set this to <strong>json</strong> as I like working with it. What is JSON? Ah, it stands for JavaScript Object Notation. It is a relatively modern, and my preferred method, for handling data within JavaScript. If you&#8217;re used to PHP, think of JSON as a multi-dimensional array. It allows us to handle groups of data as one &#8220;object&#8221; (or variable if you prefer). We generally use dot notation to access it&#8217;s properties. I&#8217;m sure I&#8217;ll explain JSON in greater detail in the future &#8211; but for now here&#8217;s a <a href="http://en.wikipedia.org/wiki/JSON">more-than-generous explanation</a>.</p>
<p>Ok so our four parameters are set:</p>
<ul>
<li>Send Data To This Page</li>
<li>Send This Data To That Page</li>
<li>Run This Function When We Get a Response From That Page</li>
<li>I&#8217;m Expecting The Data To Be Returned Like This</li>
</ul>
<p>Ok so that&#8217;s our four main parameters set for our <strong>$.post()</strong> function. Before we check out the server-side handling of this AJAX call, let&#8217;s just take a quick peek at our success function (which is our third parameter in our AJAX call):</p>
<pre name="code" class="javascript">
function(data){
	$('#loading').hide('fast');
	alert("Your name is: " + data.name + "\nYour age is: " + data.age);
}
</pre>
<p>The first thing we&#8217;re doing is hiding the <strong>loading</strong> div (as our data has now loaded), and then we&#8217;re just doing a simple alert with the data we received. To populate the alert, we&#8217;re just using JSON to retrieve the data using data.<strong>VARIABLE</strong>. In this case, data.<strong>name</strong> and data.<strong>age</strong>.</p>
<p>How do we know we&#8217;re going to have <strong>name</strong> and <strong>age</strong> sent back as our <strong>data</strong> JavaScript Object? That all comes down to the final part &#8211; the server-side handling of our AJAX form, and I think you&#8217;ll be surprised to see just how simple it really is!</p>
<h2>Handling the AJAX Form, Server-Side</h2>
<p>At the very top of our page &#8211; where I like to handle my form posts (on the same page as the form, not on a different page), we have the following code:</p>
<pre name="code" class="php">
&lt;?php
if($_POST['formPosted'] == 'true'){
	$returnData = array(2);
	$returnData['name'] = $_POST['yourName'];
	$returnData['age']	= $_POST['yourAge'];
	echo json_encode($returnData);
	exit;
}
?&gt;
</pre>
<p>That&#8217;s it!</p>
<p>We know that we can handle the form variables using the <strong>$_POST</strong> super global, as we used the <strong>$.post()</strong> function via jQuery. We also know that we&#8217;re sending ALL form elements, because we used the serialize() method, again provided by jQuery. This means that we can access the <strong>yourName</strong> and <strong>yourAge</strong> form elements (note that we&#8217;re also checking that <strong>formPosted</strong> is true before running this block of code &#8211; this was our hidden variable in our form remember?).</p>
<p>We&#8217;re then simply (and very simply for the purposes of this tutorial), creating an array called <strong>$returnData</strong>, and adding the value of <strong>yourName</strong> to <strong>$returnData['name']</strong>, and <strong>yourAge</strong> to <strong>$returnData['age']</strong>. Notice something here? The PHP array we have just created now has two elements, <strong>name</strong> and <strong>age</strong>.</p>
<p>All we need to do now is to encode our array as JSON, and echo it out, which we do in one line:</p>
<pre name="code" class="php">
echo json_encode($returnData);
</pre>
<p>Then <strong>most importantly</strong>, we exit. We MUST exit here, otherwise the remainder of the page would continue to load, and also be sent back to our JavaScript function which is waiting for the data. ALWAYS exit once you have dealt with an AJAX call. The point is to provide the data requested and that&#8217;s it. If we sent it all back, it would malform the JSON we&#8217;re echoing out, and as such, break our functionality. Not to mention it&#8217;d also be completely pointless, as we&#8217;re loading the entire page again!</p>
<p>So there you have it! Any questions, comments or criticism &#8211; please post in the comments, and don&#8217;t forget that there&#8217;s a:</p>
<h2><a target="_blank" href="http://edrackham.com/tutorials/ajax-form-tutorial/">DEMO: HERE</a></h2>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/ajax-form-tutorial/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Create a Textarea Character Counter / Limiter Using jQuery</title>
		<link>http://edrackham.com/javascript/how-to-create-a-textarea-character-counter-limiter-using-jquery/</link>
		<comments>http://edrackham.com/javascript/how-to-create-a-textarea-character-counter-limiter-using-jquery/#comments</comments>
		<pubDate>Mon, 04 Oct 2010 20:07:52 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Character Counter]]></category>
		<category><![CDATA[Code Snippet]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[Textarea]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=83</guid>
		<description><![CDATA[Need to limit the number of characters that are allowed to be entered into a textarea? I&#8217;ve crafted a little snippet that you can drop into your projects to achieve just that! It also provides a counter to the user, showing how many characters are remaining as they type. Your browser doesn&#8217;t support IFRAMES. You [...]]]></description>
			<content:encoded><![CDATA[<p>Need to limit the number of characters that are allowed to be entered into a textarea? I&#8217;ve crafted a little snippet that you can drop into your projects to achieve just that! It also provides a counter to the user, showing how many characters are remaining as they type.</p>
<p><iframe frameborder="0" src="http://edrackham.com/tutorials/textarea-character-counter-using-jquery/?iframe" height="80px" width="460px" scrolling="no">Your browser doesn&#8217;t support IFRAMES. You can see the textarea character counter <a href="http://edrackham.com/tutorials/textarea-character-counter-using-jquery/" title="Textarea Character Counter">here</a>.</iframe></p>
<p>This could be extended pretty easily, so that it works on multiple textareas, or even as a jQuery plugin.<span id="more-83"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>Show Me the Code</h2>
<p>If you don&#8217;t need to read the breakdown of this tutorial, you can simply just copy the code below and read no further!</p>
<h3>The Javascript</h3>
<pre name="code" class="javascript">
&lt;script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;

&lt;script type="text/javascript" language="javascript"&gt;
google.load("jquery", "1.4.2");

var characterLimit = 150;

google.setOnLoadCallback(function(){

	$('#remainingCharacters').html(characterLimit);

	$('#myTextarea').bind('keyup', function(){
		var charactersUsed = $(this).val().length;

		if(charactersUsed > characterLimit){
			charactersUsed = characterLimit;
			$(this).val($(this).val().substr(0, characterLimit));
			$(this).scrollTop($(this)[0].scrollHeight);
		}

		var charactersRemaining = characterLimit - charactersUsed;

		$('#remainingCharacters').html(charactersRemaining);
	});
});
&lt;/script&gt;
</pre>
<h3>The HTML</h3>
<pre name="code" class="html">
<textarea id="myTextarea"></textarea>

<span id="remainingCharacters"></span> characters remaining.
</pre>
<p><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>So, How Does It All Work?</h2>
<p>Let&#8217;s start with the HTML markup. It&#8217;s pretty simple, we&#8217;re just creating a textarea, with an ID of <strong>myTextarea</strong>. We also have a paragraph below that, which has an empty span with an ID of <strong>remainingCharacters</strong>. This is where the remaining characters will be displayed to the user as they type.</p>
<h2>Google JSAPI</h2>
<p>The Javascript is a little more involved. Let&#8217;s go line-by-line:</p>
<pre name="code" class="javascript">
&lt;script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
</pre>
<p>I&#8217;ve recently started using the <a href="http://code.google.com/apis/libraries/">Google JSAPI</a> to link to my most-used Javascript libraries. For those who don&#8217;t know what the Google JSAPI is &#8211; <a href="http://code.google.com/apis/libraries/">have a read here</a>. I prefer to load jQuery this way for a number of reasons:</p>
<ul>
<li>It&#8217;s always hosted in the same place &#8211; so no having to traverse your own paths to find where your JS libraries are located</li>
<li>It saves bandwidth</li>
<li>It seems to load much faster</li>
<li>It&#8217;s very easy to bolt on other libraries you may need</li>
</ul>
<pre name="code" class="javascript">
&lt;script type="text/javascript" language="javascript"&gt;
google.load("jquery", "1.4.2");
</pre>
<p>Here, we&#8217;re starting our main Javascript block, and &#8211; using the Google JSAPI &#8211; we&#8217;re loading the jquery library, version 1.4.2.</p>
<h2>Variable Limit</h2>
<pre name="code" class="javascript">
var characterLimit = 150;
</pre>
<p>Real simple here &#8211; we&#8217;re setting a global variable to the value of our limit for the textarea. Feel free to change this value to whatever you wish.</p>
<h2>What? No $(document).ready()?</h2>
<pre name="code" class="javascript">
google.setOnLoadCallback(function(){
</pre>
<p>Nope. When you use the Google JSAPI, you should really use <strong>google.setOnLoadCallback()</strong>. This is due to the way we&#8217;re loading the jQuery. $(document).ready() may actually provide a false-positive, and execute before the jQuery has been fully loaded &#8211; therefore we should use the google on load callback &#8211; which fires once all the libraries we have requested have been included.</p>
<h2>Set the Starting Figure</h2>
<pre name="code" class="javascript">
$('#remainingCharacters').html(characterLimit);
</pre>
<p>As our <strong>remainingCharacters</strong> span in our HTML markup is empty, we need to set the value when the page loads. We could hard-code the value of the remaining characters, but this would mean that we&#8217;d have to update two places if we wanted to change the limit, not just one (the one place we need to update the character limit is on the <strong>var characterLimit = 150;</strong> line).<br />
<div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>Binding It All Up</h2>
<pre name="code" class="javascript">
$('#myTextarea').bind('keyup', function(){
	var charactersUsed = $(this).val().length;

	if(charactersUsed &gt; characterLimit){
		charactersUsed = characterLimit;
		$(this).val($(this).val().substr(0, characterLimit));
		$(this).scrollTop($(this)[0].scrollHeight);
	}

	var charactersRemaining = characterLimit - charactersUsed;

	$('#remainingCharacters').html(charactersRemaining);
});
</pre>
<p>The final bit, this <strong>bind</strong> is where all the magic happens. Firstly we&#8217;re binding a function to the &#8216;keyup&#8217; event on the element named <strong>myTextarea</strong>.</p>
<p>Inside this function we need to know how many characters have been used. We do this by calling the following:</p>
<pre name="code" class="javascript">
var charactersUsed = $(this).val().length;
</pre>
<p>Notice how we can use <strong>$(this)</strong> to reference the <strong>myTextarea</strong> element. This is a nice little bit of shorthand that comes in handy &#8211; often!</p>
<pre name="code" class="javascript">
if(charactersUsed &gt; characterLimit){
	charactersUsed = characterLimit;
	$(this).val($(this).val().substr(0, characterLimit));
	$(this).scrollTop($(this)[0].scrollHeight);
}
</pre>
<p>We then have this if statement which checks to see if the number of characters used is greater than our preset character limit. If it is greater, we know that the user has gone over their limit, and we need to do something about that. We need to trim any extra characters past our limit, and reset the focus to the bottom of the textarea. We need to set the focus to the bottom again, because when you update the text within a textarea, the focus jumps back to the top!</p>
<h2>Letting the User See How Many Characters Remain</h2>
<pre name="code" class="javascript">
var charactersRemaining = characterLimit - charactersUsed;

$('#remainingCharacters').html(charactersRemaining);
</pre>
<p>Fairly self explanatory here &#8211; we do a quick calculation to determine how many characters remain, and then update the <strong>remainingCharacters</strong> span, so the user can see how much more they can type.</p>
<p>Remember, this gets updated every time they key is released from within the textarea.</p>
<p>That concludes this tutorial! I hope it&#8217;s helped in some way. I may even release this as a simple jQuery plugin that can be used on any number of textareas.</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/javascript/how-to-create-a-textarea-character-counter-limiter-using-jquery/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>How to Convert PHP Multidimensional Array to Javascript Object (using jQuery)</title>
		<link>http://edrackham.com/php/how-to-convert-php-multidimensional-array-to-javascript-object-using-jquery/</link>
		<comments>http://edrackham.com/php/how-to-convert-php-multidimensional-array-to-javascript-object-using-jquery/#comments</comments>
		<pubDate>Wed, 29 Sep 2010 20:50:17 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Javascript Object]]></category>
		<category><![CDATA[Parsing JSON]]></category>
		<category><![CDATA[PHP Arrays]]></category>

		<guid isPermaLink="false">http://edrackham.com/?p=77</guid>
		<description><![CDATA[I was working on a project today, and I needed to convert a PHP based multidimensional array into a Javascript array, so that I could use it for a dynamic select dropdown (depending on the top level category chosen, the next level select dropdown would be populated with the child elements of the top level [...]]]></description>
			<content:encoded><![CDATA[<p>I was working on a project today, and I needed to convert a PHP based multidimensional array into a Javascript array, so that I could use it for a dynamic select dropdown (depending on the top level category chosen, the next level select dropdown would be populated with the child elements of the top level category options &#8211; if you follow me!).</p>
<p>Anyway, I soon realised that converting the PHP array into a Javascript <em><strong>array</strong></em> was a bad idea, as converting it to a Javascript <em><strong>object</strong></em> would be much much better.<br />
<span id="more-77"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p>To convert a PHP array (single dimensional, or multidimensional) you simply need to <strong>double</strong> JSON encode the array. This tutorial relies on jQuery to parse the JSON (using $.parseJSON()), but this isn&#8217;t at all necessary &#8211; there are other methods to parse JSON. Let&#8217;s use the following PHP array as our example:</p>
<pre name="code" class="php">
$aCoders = array();
$aCoders['Ed']['age'] = 25;
$aCoders['Ed']['languages'] = array('PHP', 'MySQL', 'JavaScript', 'Objective-C', 'HTML', 'CSS');
$aCoders['Sarah']['age'] = 25;
$aCoders['Sarah']['languages'] = array('HTML', 'CSS');
</pre>
<p>Now we want to use that object with JavaScript. Rather than firing off an AJAX request to get the results we want, seeing as the array is fairly small, we may as well render it in the browser when the page loads &#8211; to save on bandwidth and unnecessary requests to the server. To make this array become accessible in Javascript (using jQuery), use the following:</p>
<pre name="code" class="javascript">
var coders = $.parseJSON(&lt;?php print json_encode(json_encode($aCoders)); ?&gt;);
</pre>
<p>Yep &#8211; you need to <strong>double encode</strong> the array. This is the key that took me a while to figure out. It adds extra slashes each time you encode, therefore making it render-able in Javascript the second time you encode it.</p>
<p>You can now access your array data using methods similar to the following:</p>
<pre name="code" class="javascript">
for(var language in coders.Ed.languages){
  alert('Ed can code in ' + language);
}
</pre>
<p>Note that javascript objects use dot notation to access the data. If you have a numeric key within your PHP array, you must access it via Javascript using square brackets. For example:</p>
<pre name="code" class="javascript">
alert(object[5].name);
</pre>
<p>I hope this helps you to better understand how to translate PHP arrays into Javascript objects, and realise when it&#8217;s a good idea to use them, and when it&#8217;s still a good idea to just grab what you need by means of an AJAX request.</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/how-to-convert-php-multidimensional-array-to-javascript-object-using-jquery/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Beginner&#8217;s Guide to Writing a jQuery Plugin</title>
		<link>http://edrackham.com/javascript/beginners-guide-to-writing-a-jquery-plugin/</link>
		<comments>http://edrackham.com/javascript/beginners-guide-to-writing-a-jquery-plugin/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 20:55:55 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[authoring]]></category>
		<category><![CDATA[default text]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[simple tutorial]]></category>

		<guid isPermaLink="false">http://edrackham.com/javascript/beginners-guide-to-writing-a-jquery-plugin/</guid>
		<description><![CDATA[Lots of tutorials coming up in the next few days &#8211; seeing as you guys are actually enjoying them! This is a really simple tutorial on how to write a jQuery plugin. It&#8217;s also a usable &#8220;Default Text&#8221; plugin, which sets some preset text in a form input, which clears when you focus the fiels. [...]]]></description>
			<content:encoded><![CDATA[<p>Lots of tutorials coming up in the next few days &#8211; seeing as you guys are actually enjoying them! This is a really simple tutorial on how to write a jQuery plugin. It&#8217;s also a usable &#8220;Default Text&#8221; plugin, which sets some preset text in a form input, which clears when you focus the fiels.</p>
<p>It&#8217;s not as comprehensive as some other articles out there, as I wanted to keep this nice and simple. If you&#8217;re like me, you just want the simple tutorial &#8211; as you&#8217;ll enjoy building on it in the future!<br />
<span id="more-33"></span><div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>Gimmie the code. Now.</h2>
<p>Let&#8217;s do what I usually do &#8211; start with the entire code snippet, so if you like &#8211; just take it and run! If you want a break down, keep reading on after the code.</p>
<h3><a href="http://github.com/a1phanumeric/jQuery-Default-Text-Plugin/archives/master">Download the Plugin Here</a></h3>
<h3><a href="http://github.com/a1phanumeric/jQuery-Default-Text-Plugin/">Documentation / Usage Here</a></h3>
<h3><a href="http://edrackham.com/jquery/default_text/">Demo the jQuery Default Text Plugin</a></h3>
<pre name="code" class="javascript">
$.fn.DefaultText = function(options) {

    var defaults = {
        inactiveClass:      '',
        inactiveFontStyle:  'italic',
        inactiveColour:     'rgb(204,204,204)',
        activeFontStyle:    'normal',
        activeColour:       'rgb(0,0,0)'
    };

    var opts = $.extend(defaults, options);

    $(this).each(function(){

        if(opts.inactiveClass != ''){
            $(this).addClass(opts.inactiveClass);
        }else{
            $(this).css({'font-style' : opts.inactiveFontStyle, 'color' : opts.inactiveColour});
        }

        $(this).bind('focus', function(){
            if($(this).val() == $(this).attr('title')){
                if(opts.inactiveClass != ''){
                    $(this).removeClass(opts.inactiveClass);
                }else{
                    $(this).css({'font-style' : opts.activeFontStyle, 'color' : opts.activeColour});
                }

                $(this).val('');
            }
        });

        $(this).bind('blur', function(){
            if($(this).val() == ''){
                if(opts.inactiveClass != ''){
                    $(this).addClass(opts.inactiveClass);
                }else{
                    $(this).css({'font-style' : opts.inactiveFontStyle, 'color' : opts.inactiveColour});
                }

                $(this).val($(this).attr('title'));
            }
        });

        $(this).blur();
        $(this).val($(this).attr('title'));

    });

};</pre>
<p>Simply save this as whatever you want (I used <strong>jquery.DefaultText.js</strong>) and start using it now! Docs on how to use can be found <a href="http://github.com/a1phanumeric/jQuery-Default-Text-Plugin">on my Github repo</a>.<br />
<div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<h2>So how do I make a jQuery plugin?</h2>
<p>It&#8217;s really, really simple. It&#8217;s probably much more simple than you think! The first line is very important:</p>
<pre name="code" class="javascript">$.fn.DefaultText = function(options) {</pre>
<p>This is where we declare the plugin. <strong>DefaultText</strong> is the name of this plugin. You can name yours whatever you like. As you can see we&#8217;re sending one parameter <strong>options</strong> to the plugin function. This is a completely optional parameter, but is used to send parameters to our plugin as explained in a moment.</p>
<pre name="code" class="javascript">    var defaults = {
        inactiveClass:      '',
        inactiveFontStyle:  'italic',
        inactiveColour:     'rgb(204,204,204)',
        activeFontStyle:    'normal',
        activeColour:       'rgb(0,0,0)'
    };</pre>
<p>This is a list of our default parameters. You can see we have a placeholder for <strong>inactiveClass</strong>, and four other parameters. Two for a default inactive state (when the textfield is blurred [no focus on it]) and two for when the user has focused the text field. I coded the plugin like this for two reasons.</p>
<p>1. I like to have a fallback without always having to rely on yet another CSS definition (that many jQuery plugins require)<br />
2. Because this tutorial would be pretty bare without it!</p>
<h2>jQuery Plugin Options</h2>
<p>The next line allows us to extend the default parameters (stored in the variable <strong>defaults</strong>) with options passed through the plugin. Basically, this line:</p>
<pre name="code" class="javascript">var opts = $.extend(defaults, options);</pre>
<p>merges the defaults with any options passed through, for example, like this:</p>
<pre name="code" class="javascript">$("#textField").DefaultText({inactiveClass: 'myInactiveClass'});</pre>
<p>Any parameters passed through in this way will <strong>overwrite</strong> the defaults as set in the plugin.</p>
<h2>The meat of the plugin</h2>
<pre name="code" class="javascript">$(this).each(function(){</pre>
<p>This is where it all gets going. This line basically initiates the loop through all of the matched elements when we declared the plugin. If we had a form like so:</p>
<pre name="code" class="html">
<form>
<input type="text" title="First Input" value="" class="defaultTextInput" />
<input type="text" title="Second Input" value="" class="defaultTextInput" />
<input type="text" title="Third Input" value="" class="defaultTextInput" />
<input type="submit" value="Submit" />
</form>
</pre>
<p>And initialised the plugin using the following:</p>
<pre name="code" class="javascript">$(".defaultTextInput").DefaultText();</pre>
<p>Then the loop would match all three of the text inputs, with the class <strong>defaultTextInput</strong>. So for each element we have found, we need to run some JavaScript goodness!</p>
<p>Firstly, we are setting the default state of the inputs, as their unfocused states (in this case, the font will be a light grey, and italicised).</p>
<pre name="code" class="javascript">        if(opts.inactiveClass != ''){
            $(this).addClass(opts.inactiveClass);
        }else{
            $(this).css({'font-style' : opts.inactiveFontStyle, 'color' : opts.inactiveColour});
        }</pre>
<p>We have an if statement, just so we know whether we&#8217;re using a class to style the default look/feel of the input, or whether to use the inactive font style and colour. It&#8217;s important to note here, if the user has chosen to use a class, then that will take precedence over the inactiveFontStyle and inactiveColour.<br />
<div align="center" style="margin-bottom: 20px;">
<script type="text/javascript"><!--
google_ad_client = "pub-4159646232668987";
google_ad_slot = "5003066961";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p>Next, we bind the focus() function to each of the inputs. Remember, this will bind to EVERY matched element, as we&#8217;re still inside the <strong>$(this).each()</strong> loop.</p>
<pre name="code" class="javascript">        $(this).bind('focus', function(){
            if($(this).val() == $(this).attr('title')){
                if(opts.inactiveClass != ''){
                    $(this).removeClass(opts.inactiveClass);
                }else{
                    $(this).css({'font-style' : opts.activeFontStyle, 'color' : opts.activeColour});
                }

                $(this).val('');
            }
        });</pre>
<p>This simple function checks to see if the value of the text input matches the title attribute of the input. If it does, it removes the default styling &#8211; then sets the value to an empty string &#8211; ready for writing into.</p>
<p>In a similar fashion to the above, this next block controls the blur() functionality for each text input:</p>
<pre name="code" class="javascript">        $(this).bind('blur', function(){
            if($(this).val() == ''){
                if(opts.inactiveClass != ''){
                    $(this).addClass(opts.inactiveClass);
                }else{
                    $(this).css({'font-style' : opts.inactiveFontStyle, 'color' : opts.inactiveColour});
                }

                $(this).val($(this).attr('title'));
            }
        });</pre>
<p>This time, we looking to see if the value of the text input is empty. If it is, we put the default styling back on for that text input (the same way we did at the beginning, if the inactiveClass is present &#8211; it uses that, otherwise it uses the inactiveFontStyle and inactiveColour values). We then put the default text &#8211; stored in the title attribute of the element &#8211; as the value of the text input.</p>
<pre name="code" class="javascript">        $(this).blur();
        $(this).val($(this).attr('title'));

    });

};</pre>
<p>The final part of this jQuery plugin tutorial is just making sure that every text input is blurred, and has the title attribute as the default text. It&#8217;s not really necessary at all &#8211; it&#8217;s just there to show how you can run other functionality within the meaty loop. We&#8217;re then closing the each() loop and closing the function.</p>
<h2>That&#8217;s it! Easy!</h2>
<p>It&#8217;s really as simple as that! You can now go and author your own uber-1337 jQuery plugins! Don&#8217;t forget to show me what you&#8217;ve made &#8211; I might even feature the best plugins on this site for everyone to use!</p>
<h3><a href="http://github.com/a1phanumeric/jQuery-Default-Text-Plugin/archives/master">Download the Plugin Here</a></h3>
<h3><a href="http://github.com/a1phanumeric/jQuery-Default-Text-Plugin/">Documentation / Usage Here</a></h3>
<h3><a href="http://edrackham.com/jquery/default_text/">Demo the jQuery Default Text Plugin</a></h3>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/javascript/beginners-guide-to-writing-a-jquery-plugin/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Solution to Form Submit 403 Error</title>
		<link>http://edrackham.com/javascript/solution-to-form-submit-403-error/</link>
		<comments>http://edrackham.com/javascript/solution-to-form-submit-403-error/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 14:51:25 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Form Submit 403]]></category>
		<category><![CDATA[mod_security]]></category>
		<category><![CDATA[Solution]]></category>

		<guid isPermaLink="false">http://edrackham.com/javascript/solution-to-form-submit-403-error/</guid>
		<description><![CDATA[Have you ever had a problem where you get a HTTP 403 error from submitting a form? Does this form have a field that submits a URL? If yes to the above two questions, I think I know the problem you&#8217;re having, and have a solution. It&#8217;s to do with mod_security (an Apache module) and [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever had a problem where you get a HTTP 403 error from submitting a form?<br />
Does this form have a field that submits a URL?</p>
<p>If <strong>yes</strong> to the above two questions, I think I know the problem you&#8217;re having, and have a solution. It&#8217;s to do with <a href="http://www.modsecurity.org/">mod_security</a> (an Apache module) and the &#8216;http://&#8217; part of the URL.</p>
<p><span id="more-27"></span></p>
<p>The obvious answer is to tell you to go and modify the module yourself, but many of you don&#8217;t have access to those kind of modifications due to hosting company restrictions. My simple solution uses JavaScript to remove the &#8216;http://&#8217; part from the URL.</p>
<p>Let&#8217;s start by saying you have a form that looks something like the following:</p>
<pre name="code" class="html">
<form id="SendDataForm" name="SendDataForm" method="post" action="page.php">
	<label for="FullName">Full Name:</label>
<input type="text" name="FullName" id="FullName" />
	
	<label for="EmailAddress">Email Address:</label>
<input type="text" name="EmailAddress" id="EmailAddress" />
	
	<label for="WebsiteAddress">Website Address:</label>
<input type="text" name="WebsiteAddress" id="WebsiteAddress" />
	
	<label for="SendForm">&nbsp;</label>
<input type="submit" name="SendForm" id="SendForm" value="Submit" />
</form>
</pre>
<p>Add the following between the <HEAD></HEAD> tags (or within a JavaScript include):</p>
<pre name="code" class="javascript">function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function MakeLinkSafe(){
	var e = document.getElementById('WebsiteAddress')
	str = trim(e.value);
	if(str.substr(0, 7) == 'http://'){
		e.value = str.substr(7);
	}
	return true;
}</pre>
<p>Then, on your form submit button, add the following:</p>
<pre name="code" class="html">onclick="MakeLinkSafe()"</pre>
<p>So that your submit button now looks like:</p>
<pre name="code" class="html">
<input type="submit" name="SendForm" id="SendForm" value="Submit" onclick="MakeLinkSafe()" /></pre>
<p>Now, when you click the submit button, it&#8217;ll invoke the JavaScript, which will remove the http:// part (if it exists). You can then modify your &#8216;action page&#8217; code to catch this element and re-add the http:// part if needs be.</p>
<p>Just remember to update the</p>
<pre name="code" class="javascript">document.getElementById('WebsiteAddress')</pre>
<p>to reflect the ID of the element that collects the URL on your form.</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/javascript/solution-to-form-submit-403-error/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

