<?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 Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/tag/ajax/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/tag/ajax/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Mon, 12 Aug 2024 15:11:18 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Working with jQuery&#8217;s AJAX, Promises and Deferred objects</title>
		<link>https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/</link>
					<comments>https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 11 Feb 2017 21:17:12 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6022</guid>

					<description><![CDATA[<p>jQuery&#8217;s implementation of making AJAX calls is quite easy to understand. There is $.ajax(), $.get(), $getJSON(), $.post() &#8211; which are all xhr requests, just different ways of writing it. It probably has the most straightforward syntax available and that&#8217;s why developers continue to use it, more than other libraries.The funny thing is, once we get [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/">Working with jQuery&#8217;s AJAX, Promises and Deferred objects</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>jQuery&#8217;s implementation of making AJAX calls is quite easy to understand. There is <em>$.ajax(), $.get(), $getJSON(), $.post()</em> &#8211; which are all xhr requests, just different ways of writing it. It probably has the most straightforward syntax available and that&#8217;s why developers continue to use it, more than other libraries.<br><img fetchpriority="high" decoding="async" width="700" height="200" class="alignnone size-full wp-image-6042" src="https://michaelsoriano.com/wp-content/uploads/2017/02/jquery-ajax.png" alt="" srcset="https://michaelsoriano.com/wp-content/uploads/2017/02/jquery-ajax.png 700w, https://michaelsoriano.com/wp-content/uploads/2017/02/jquery-ajax-300x86.png 300w" sizes="(max-width: 700px) 100vw, 700px" /><br>The funny thing is, once we get to know it, we almost want to do everything via AJAX. From fetching and posting data to grabbing static files and compiling templates, &#8211; you name it. Before you know it, we&#8217;re making AJAX calls all over the place. It can get ugly really fast. Without knowing Promises and Deferred, our code syntax will get messy.</p>



<p>For instance, you&#8217;ve probably run into this problem at one point.<br>Notice our &#8220;results&#8221; array is empty after we run our function:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData (){
   $.get('/page.php',function(data){
       console.log(data) //filled!
       return data;
   });
}
var results = getData();
console.log(results); //empty!
</code></pre>



<p>The issue here is our getData() method continues to run even before our AJAX call finishes. So naturally, our results will log empty. One thing we DON&#8217;T want to do is to continue our logic inside the <em>$.get()</em> utility!</p>



<h3 class="wp-block-heading">Enter Promises</h3>



<p>jQuery have promises implemented with their AJAX methods. In a nutshell, they are utilities that allow us to work with events that have completed or put them in queues or chain them &#8211; all of that good stuff.  In our case, we need a &#8220;<em>promise</em>&#8220;. This allows us to interact with our AJAX requests &#8211; well outside our <em>$.get()</em> utility. So we can continue with our logic as designed.</p>



<p>So let&#8217;s solve our issue with <strong>.done() </strong>&#8211; which is a method that comes with <em>$.get()</em>:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData (){
   return $.get('/page.php');
}
getData().done(function(data){
  console.log(results); //filled!
});</code></pre>



<p>As you can see, we can use our function getData() &#8211; anywhere in our code as we&#8217;ve intended it to be. Note that there is also <strong>.fail(), .always()&nbsp;</strong> &#8211; which are the other methods for our $.get() promise object. <em>.fail()</em> for &#8211; when our call fails, <em>.always()</em>&nbsp;occurs every time it runs. The syntax is very self-explanatory.<br>Now we can also do this:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">getData().fail(function(error){
  console.log(error); //some error handling
}).always(function(){
  //something that happens every time...
});</code></pre>



<p>Which may serve as a global error handler for our getData() function.</p>



<p>You can also do both!</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData (){
   var ajax = $.get('/page.php',function(data){
     //do something with data here
   });
   return ajax;
}
getData().done(function(data){
  //do something else with data here
});</code></pre>



<p>So our method getData() &#8211; will always run our success function inside <em>$.get()</em>, while we use <strong>.done() </strong>&#8211; everywhere else in our code.</p>



<h3 class="wp-block-heading">Multiple AJAX calls</h3>



<p>What about multiple (different)&nbsp;AJAX calls? Something like below:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData1 (){
   return $.get('/page1.php');
}
function getData2 (){
   return $.get('/page2.php');
}
function getData3 (){
   return $.get('/page3.php');
}
getData1().done(function(data){
  //do something here
});
getData2().done(function(data){
  //do something here
});
getData3().done(function(data){
  //do something here
});</code></pre>



<p>This is fine, but it looks rather clumsy don&#8217;t you think. There is a method called <strong>.when() </strong>&#8211; which deals with stuff like this.</p>



<p>Instead of writing multiple <strong>.done(), </strong>we can elegantly compile them into a single block. We still get access to the same objects &#8211; as if we&#8217;re dealing with each AJAX call individually.</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData1 (){
   return $.get('/page1.php');
}
function getData2 (){
   return $.get('/page2.php');
}
function getData3 (){
   return $.get('/page3.php');
}
$.when(getData1(),getData2(),getData3()).done(function(r1,r2,r3){
   console.log(r1) //[data, status, xhrObj]
   console.log(r2) //[data, status, xhrObj]
   console.log(r3) //[data, status, xhrObj]
})</code></pre>



<p>Note that each response returns an array. So for example you want to access the data of the first response, you do a <strong>r1[0]</strong> and so forth.</p>



<h3 class="wp-block-heading">Multiple <em>Dynamic</em> AJAX calls</h3>



<p>Now this one is tricky. It has been asked in <a href="http://stackoverflow.com/questions/19614354/dynamic-multiple-deferred-jquery-ajax-calls">StackOverflow</a> &#8211; which has an answer I would have not guessed. First thing is to get our requests in an array format. So this will be the dynamic part and it&#8217;s up to you how you want to design that. Now, <em>$.when</em> is smart enough to process the calls &#8211; if you pass them in single or an array.</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">var requests = [ //this will be the dynamic part
  $.get('page1.php'),
  $.get('page2.php'),
  $.get('page3.php')
]
$.when.apply($,requests).done(function(){
  console.log(arguments); //array of responses [0][data, status, xhrObj],[1][data, status, xhrObj]...
})</code></pre>



<p>But note that we use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">.apply</a> after <em>$.when</em> This is so we can have access to a special variable called &#8220;arguments&#8221;. The arguments hold the responses from our array of calls, in a multi-dimensional array format.</p>



<p>As you can see, our promise is still in-tact and does it&#8217;s thing for dynamic AJAX calls.</p>



<h3 class="wp-block-heading">$.Deferred()</h3>



<p>As the method implies, <em>$.Deferred()</em> is to put in on hold, until you&#8217;re ready to interact with it. <em>$.Deferred()</em> is useful when we have actions such as multiple AJAX calls and we want to continue interacting with them at a later time.</p>



<p>Building on our example, let&#8217;s wrap our <em>$.when()</em> inside<b> </b>a function so we can call it later. Let&#8217;s use the <strong>.resolve()</strong> function of $.Deferred to illustrate:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData1 (){
   return $.get('/page1.php');
}
function getData2 (){
   return $.get('/page2.php');
}
function getData3 (){
   return $.get('/page3.php');
}
function defCalls(){
   var def = $.Deferred();
   $.when(getData1(),getData2(),getData3()).done(function(){
     setTimeout(function(){
       def.resolve();
     },2000)
   })
   return def.promise();
}
defCalls();//returns the promise object</code></pre>



<p>You see that we are delaying our .resolve by 2 seconds using setTimeout(). You will see our def.promise() will take 2 seconds to return.</p>



<p>Also, now we have an accessible <em>defCalls()</em> promise object that we can use at a later time:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">defCalls().done(function(){
  //do something here
})</code></pre>



<p>You can also pass parameters&nbsp;to <em>.resolve() &#8211; </em>for later use in our defCalls() promise object. For example, the responses that came back from our call:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function defCalls(){
   var def = $.Deferred();
   $.when(getData1(),getData2(),getData3()).done(function(r1,r2,r3){
     def.resolve(r1,r2,r3);
   })
   return def.promise();
}
defCalls().done(function(d1,d2,d3){
   //now we have access to data...
})</code></pre>



<p>What about multiple dynamic calls? We already learned about .apply(). We simply do the same thing so we can pass &#8220;arguments&#8221;:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function defCalls(){
   var def = $.Deferred();
   var requests = [
     getData1(),
     getData2()
   ]
   $.when.apply($,requests).done(function(){
     def.resolve(arguments);
   })
   return def.promise();
}
defCalls().done(function(arr){
   //now we have access to array of data
   console.log(arr);
})</code></pre>



<p>Lastly, let&#8217;s just say we want to create an action for failed events, we use the <strong>.reject()</strong> method for that:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function defCalls(){
   var def = $.Deferred();
   $.when(getData1(),getData2(),getData3()).fail(function(){
     def.reject();
   })
   return def.promise();
}
defCalls().fail(function(){
   //do something here
})</code></pre>



<p>As you can see, there many benefits in using promises and deferred objects &#8211; especially in asynchronous programming with jQuery&#8217;s AJAX. Not only that it will make your code easier to read. But it also makes it easier to debug, well factored and organized &#8211; the way jQuery intended it to be.</p>



<p>I would like to read comments on how you&#8217;re using these objects in your own code. Please leave them below.</p>
<p>The post <a href="https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/">Working with jQuery&#8217;s AJAX, Promises and Deferred objects</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/feed/</wfw:commentRss>
			<slash:comments>22</slash:comments>
		
		
			</item>
		<item>
		<title>How to do Ajax form validation with inline error messages &#8211; without using a plugin</title>
		<link>https://michaelsoriano.com/how-to-ajax-validate-forms/</link>
					<comments>https://michaelsoriano.com/how-to-ajax-validate-forms/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 14 Mar 2015 17:39:05 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=4386</guid>

					<description><![CDATA[<p>When in comes to validating forms, there are basically two techniques you can use: 1) Server-side validation and 2) Client-side validation. Server-side validation is when form data is submitted, server analyzes then returns the user back to the form when items are invalid. Client-side on the other hand, is when Javascript analyses the fields before [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/how-to-ajax-validate-forms/">How to do Ajax form validation with inline error messages &#8211; without using a plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>When in comes to validating forms, there are basically two techniques you can use: 1) Server-side validation and 2) Client-side validation. Server-side validation is when form data is submitted, server analyzes then returns the user back to the form when items are invalid. Client-side on the other hand, is when Javascript analyses the fields before actually submitting the data to the server.<br />
<strong>Update 4/2/2016:</strong> &#8211; The code below is not meant to be a &#8220;copy and paste&#8221; type of thing. You will need some PHP and Javascript debugging experience to successfully integrate into your project.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-inline-errors.gif" alt="ajax-inline-errors" width="471" height="282" class="alignnone size-full wp-image-4387" /><br />
Plenty argue (including myself), that server side validation is more secure. This is because client side validation can be manipulated (or simply turned off). But the bad thing about server side validation &#8211; is you see the page refresh. This is considered to be <a href="http://fearlessflyer.com/10-common-ui-mistakes-and-how-to-avoid-them/">bad user experience</a> &#8211; especially in mobile.<br />
I&#8217;ve seen solutions where they use both server side and client side &#8211; with validation rules in Javascript and their server language. But that&#8217;s a bit redundant isn&#8217;t it? Plus think of the maintenance of code that you have to do. Wouldn&#8217;t it be nice to combine both?</p>
<h3>Combining both techniques</h3>
<p>What we&#8217;re trying to achieve is have the security of server side validation, the elegance of displaying the errors inline, as well as have a fall back behavior. So even when users turn off Javascript &#8211; you will see the same error messages. Oh and of course, we will also have the good user experience of the page not refreshing when there&#8217;s errors.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-errors2.jpg" alt="ajax-errors2" width="643" height="377" class="alignnone size-full noborder wp-image-4388" /><br />
Keep in mind that you will need a bit of programming know how &#8211; especially in PHP and Javascript. Ready to get started? Let&#8217;s begin.</p>
<h3>The Markup</h3>
<p>We start with a regular form. The submit action would be a processing page where our server side logic will take place. You can also have the processing page the same as the page where the form is. But I like to keep files separate. Copy the code below into your HTML:</p>
<pre>
<form  action="process.php" method="post">
  <label>First Name</label>
  <input name="first_name" type="text"  />
  <label>Email</label>
  <input name="email" type="text"  />
  <input type="submit" value="Submit" />
</form>
</pre>
<p>Nothing fancy here. Just a regular form and a couple of fields. Remember to make your field names unique &#8211; for this is what we&#8217;ll use to validate our form.</p>
<h3>The Processing Page</h3>
<p>So when our form submits, it passes the $_POST array to this page. If you&#8217;re new to validating forms, the code below simply goes through the array and checks it against our rules for each field. Note that in our case &#8211; I&#8217;m simply checking if first name and email is empty. Of course in the real world, you will have to check for valid email and such.</p>
<pre>
session_start();
if(isset($_POST)){
  	if (empty($_POST['first_name'])) {
		$_SESSION['errors'][‘first_name'] = ‘First name is missing’;
        	}
	if (empty($_POST[‘email’])) {
		$_SESSION['errors'][‘email'] = ‘email is missing’;
        	}
        if(count($_SESSION['errors']) > 0){
	    //This is for ajax requests:
            if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                echo json_encode($_SESSION['errors']);
                exit;
             }
	    //This is when Javascript is turned off:
           echo “<ul>”;
           foreach($_SESSION['errors'] as $key => $value){
	      echo “<li>” . $value . “</li>”;
           }
           echo “</ul>”;exit;
    }else{
	//form validation successful - process data here!!!!
   }
}
</pre>
<p>The key to the code above is the check for an Ajax request. Notice the json_encode() method. This is when it&#8217;s an Ajax request and we simply echo our error array in JSON format. We will need this to format our inline messages later. The rest of the code is simply handled as if it&#8217;s regular server side processing.<br />
Again, notice the part where if it&#8217;s NOT an Ajax request &#8211; we simply echo out a list of our validation errors. You would probably want to style this better, or even echo it out in the same page as the form. But for the sake of our tutorial, I want to make it short and concise.</p>
<h3>Our Javascript</h3>
<p>I prefer to write jQuery, so the code below will only work if jQuery is included. The code below is to be added to our form page:</p>
<pre>
var data = {};
$(document).ready(function() {
  $('input[type="submit"]').on('click', function() {
      resetErrors();
      var url = 'process.php';
      $.each($('form input, form select'), function(i, v) {
          if (v.type !== 'submit') {
              data[v.name] = v.value;
          }
      }); //end each
      $.ajax({
          dataType: 'json',
          type: 'POST',
          url: url,
          data: data,
          success: function(resp) {
              if (resp === true) {
                  	//successful validation
                      $('form').submit();
                  	return false;
              } else {
                  $.each(resp, function(i, v) {
	        console.log(i + " => " + v); // view in console for error messages
                      var msg = '<label class="error" for="'+i+'">'+v+'</label>';
                      $('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg);
                  });
                  var keys = Object.keys(resp);
                  $('input[name="'+keys[0]+'"]').focus();
              }
              return false;
          },
          error: function() {
              console.log('there was a problem checking the fields');
          }
      });
      return false;
  });
});
function resetErrors() {
    $('form input, form select').removeClass('inputTxtError');
    $('label.error').remove();
}
</pre>
<p>Plenty of things going on above. Of course everything is wrapped inside our document.ready() handler, then we put a .click() for our submit button. So every time we click the submit button, we go through each field in the form and create a data object. This object contains the field names and their respective values (you can also use jQuery&#8217;s .serialize() for this purpose).<br />
We make an Ajax call to our processing page &#8211; where it does the validation in our PHP code previously. Now, remember our server side will echo a JSON object with our field names and error messages? We simply handle this by adding an error class and adding a &#8220;label&#8221; with the message through jQuery&#8217;s .after() function.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-errors4.jpg" alt="ajax-errors4" width="746" height="327" class="alignnone size-full wp-image-4390" /><br />
Of course, if there&#8217;s no errors &#8211; the form does a hard .submit() &#8211; to the same processing page and handled accordingly.</p>
<h3>Our CSS</h3>
<p>Of course, we have add our styling so our field will look like our screenshots above. Simply add this code inside style tags.</p>
<pre>
.error {
   color: #ff0000;
   font-size: 12px;
   margin-top: 5px;
   margin-bottom: 0;
}
.inputTxtError {
   border: 1px solid #ff0000;
   color: #0e0e0e;
}
</pre>
<p>Again, the styles are real basic and you probably want to do better in your own forms.</p>
<h3>Conclusion</h3>
<p>So there you have it. We&#8217;ve combined best of both worlds: server side and client side validation in one solution (thanks to Ajax). Our code has clear separation and very manageable. If a field validation rule has to change &#8211; we only need to change it in one place: the server code. Also, our users will benefit from our friendly form &#8211; and the way it gracefully tells them when they&#8217;ve missed a field and such.<br />
Let me know your thoughts and if you think this solution is a good fit for your projects. </p>
<p>The post <a href="https://michaelsoriano.com/how-to-ajax-validate-forms/">How to do Ajax form validation with inline error messages &#8211; without using a plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/how-to-ajax-validate-forms/feed/</wfw:commentRss>
			<slash:comments>40</slash:comments>
		
		
			</item>
	</channel>
</rss>
