<?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; AJAX</title>
	<atom:link href="http://edrackham.com/category/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://edrackham.com</link>
	<description>PHP, MySQL, JavaScript and Other Web Tutorials!</description>
	<lastBuildDate>Thu, 04 Aug 2011 08:30:57 +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>2</slash:comments>
		</item>
		<item>
		<title>What Beautiful PHP &amp; AJAX Looks Like</title>
		<link>http://edrackham.com/php/what-beautiful-php-ajax-looks-like/</link>
		<comments>http://edrackham.com/php/what-beautiful-php-ajax-looks-like/#comments</comments>
		<pubDate>Tue, 13 Nov 2007 15:50:36 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Beautiful]]></category>
		<category><![CDATA[Coding Standards]]></category>

		<guid isPermaLink="false">http://blog.edrackham.com/php/what-beautiful-php-ajax-looks-like/</guid>
		<description><![CDATA[I recently saw an image demonstrating What Beautiful HTML Looks Like. I&#8217;ve decided to do my own What Beautiful PHP and AJAX Looks Like image. You can also play with the actual application that this image demonstrates if you so wish! The Source This example makes use of the Prototype JavaScript library. I&#8217;m using this, [...]]]></description>
			<content:encoded><![CDATA[<p>I recently saw an image demonstrating <a href="http://www.ukimagehost.com/uploads/fff9652d04.jpg" title="It really is beautiful :]">What Beautiful HTML Looks Like</a>. I&#8217;ve decided to do my own <a href="http://img251.imageshack.us/my.php?image=beautifulphpandajaxds5.jpg" title="This is mutually as beautiful!">What Beautiful PHP and AJAX Looks Like</a> image. You can also <a href="http://edrackham.com/tutorials/beautiful_php_and_ajax_tutorial/" title="If you're interested...">play with the actual application</a> that this image demonstrates if you so wish!</p>
<p><a target='_blank' href='http://img251.imageshack.us/my.php?image=beautifulphpandajaxds5.jpg' title='What Beautiful PHP and AJAX Looks Like'><img src='http://img251.imageshack.us/img251/4563/beautifulphpandajaxds5.th.jpg' border='0'/></a></p>
<h3><a href="http://edrackham.com/tutorials/beautiful_php_and_ajax_tutorial/source.php" title="View the source of this application">The Source</a></h3>
<p>This example makes use of the <a href="http://www.prototypejs.org/">Prototype JavaScript library</a>. I&#8217;m using this, as it simplifies AJAX calls, and keeps this tutorial simple. You can <a href="http://edrackham.com/tutorials/beautiful_php_and_ajax_tutorial/source.php" title="Grab the source code of this application">view the full source here</a>, which you can view, copy and include in your AJAX applications. It contains suffice comments which should help you understand how everything works.</p>
<p>Credit for the email validation goes to <a href="http://www.ilovejackdaniels.com/php/email-address-validation/" title="I really DO love Jack Daniels!">ILoveJackDaniels</a>. It&#8217;s not bullet-proof, but suffice for this example.</p>
<p>Comments would be much appreciated on this blog entry. Positive and constructive only.</p>
]]></content:encoded>
			<wfw:commentRss>http://edrackham.com/php/what-beautiful-php-ajax-looks-like/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

