15. Ajax

About this Tutorial

Objectives

Delegates will learn to develop applications using HTML5/CSS3 and JS. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial HTML5 Web Applications
  • Develop Websites that may use web sockets, animations and geolocation

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of HTML/CSS and JavaScript will also find the content beneficial.

Prerequisites

No previous experience in web programming is required. But any experience you do have in programming will help. Also no experience in browser IDE’s is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial

Quick Access


Overview

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Web Sockets

  1. What is Ajax?
    • Ajax = “Asynchronous JavaScript with XML”
    • Ajax is a collection of technologies:
      • HTML and Cascading Style Sheets (CSS)
        • Web presentation
      • Document Object Model (DOM) and JavaScript
        • Client-side dynamic behaviour
      • XML and XSLT
        • Data exchange, transformation, and manipulation
      • XMLHttpRequest
        • A JavaScript object that performs asynchronous data retrieval
        • Available on most mainstream browsers
      • JavaScript Object Notation (JSON)
        • String representation of an object, easy to handle in client-side JavaScript code
  2. Traditional Web Applications
    T15P1
  3. Ajax Web Applications
    T15P2
  4. Uses of Ajax
    • Validate data in real time
      • Perform client-side validation before submitting to the server
    • Auto-complete data entry
      • Automatically fill in a form when the user enters some key data
    • Load data in the background
      • Browser fetches data on a client event, without blocking the UI
    • Refresh data asynchronously
      • Poll server for data updates, and/or server-side push
    • Portlets
      • Provide the level of sophistication users expect from desktop apps
  5. Advantages of Ajax
    • Bandwidth usage
      • Ajax web pages load relatively quickly, because they generate HTML locally within the browser
    • Improved user interface
      • Ajax pages feel more like a standalone app than a Web page
    • Separation of data representation vs. presentation
      • Separate the data from the formatting and styling

Lab 1: Using Ajax directly

Lab 1: Using Ajax directly
  1. Sample Application Scenario
    • Let’s see how to implement a simple Ajax Web appOpen AjaxDemo.sln in Visual Studio
      T15P3
  2. Defining the Web Page UI
    <html>
    <head>
    <script type="text/javascript">
      ... See Later on ...
    </script>
    </head>
    <body>
      <input type="text" id="myInputField" onkeyup="myOnKeyUp()" />
      <p id="myEchoField" />
    </body>
    </html>

    T15P8
  3. Creating an XMLHttpRequest Object
    • The following JavaScript code creates an XMLHttpRequest object when the HTML page is loaded:
      <script type="text/javascript">
      var request = myCreateXMLHttpRequest();
      function myCreateXMLHttpRequest() {
       try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch (e) {}
       try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
       try { return new XMLHttpRequest();          } catch (e) {}
       return null;
      }
      ...
      </script>
  4. Making Asynchronous Calls
    • Here’s the myOnKeyUp() function
      • Passes user’s text asynchronously to an ASP.NET MVC Web app
      • At the server, it invokes Echo() on the HomeController class
        function myOnKeyUp() {
         if (request != null) {
          var textField = document.getElementById("myInputField");
          var url = "/Home/Echo?text=" + textField.value;
          request.open("GET", url, true);
          request.onreadystatechange = myHandleCallback;
          request.send(null);
         }
        }
  5. Implementing the Server Functionality
    • We have implemented the server functionality as an action method in an ASP.NET MVC controller class
      • The method simple returns the same text immediately back to the client (i.e. “echo”)
        public class HomeController : Controller
        {
         ...
         public string Echo(string text)
         {
          return text;
         }
         ...
        }
  6. Implementing the Call-Back Function
    • Here’s the client-side JavaScript call-back function
      • Retrieves the response from the server and updates the UI
    • Note:
      • To retrieve a text response, use the responseText property
      • To retrieve an XML response, use the responseXML property
        function myHandleCallback() {
         if (request.readyState == 4 && request.status == 200) {
          var outputField = document.getElementById("myEchoField");
          outputField.innerHTML = request.responseText;
         }
        }
Lab
  1. In this lab, you’ll implement a Web application that showcases Ajax and Jquery. The application will be implemented as an ASP.NET MVC4 Web application.
  2. You can download the solutions from the top of the tutorial, you will be working through the initial folder and the finished article is in the final folder for referral.
  3. Familiarization
    • In Visual Studio, open the final project and run the application. The home page appears, displaying an empty text box. The purpose of the Web page is to detect keystrokes one-by-one, and to send a request to the Web server to get a list of Swansea City 2013 football players whose names match what you’ve typed in so far.
    • Try it out:
      • In the text box, type the letter y.
      • The Web page detects this keystroke and sends the text “y”to the Web server.
      • The Web server returns a list of players that contain a “y”in their name(each player has a first name, last name, and salary).
      • The Web page receives the result and displays the matches in a bulleted list as follows:
        T15P7
      • Type another letter in the text box, such as “e”. This causes the Web page to send another Ajax request, this time containing the text “ye” (i.e. it sends the entire text, not just the most recent keystroke). The Web server returns a list of players containing “ye” in their names.
    • When you’re happy with how all this works, close the browser window, return to Visual Studio, and close the Solutions project.
  4. Understanding the project structure –
    • Now open the initial project in Visual Studio. This is an ASP.NET MVC 4 Basic project. Here’s a quick overview of the project contents:
      • The Models folder contains a simple model class named Player. Each Player object will have FirstName, LastName, and Salary properties.
      • The Controllers folder contains a single controller class named HomeController. There are 2 action methods:
        • Index() serves up the one-and-only-view for the Web app.
        • FilterNames() receives a string filter parameter, which contains the text that the user typed into the text box on the web page. The method finds all players that match the filter, and returns a collection of Player objects in JSON format.
        • JSON is “JavaScript Object Notation” effectively a string representation of an object that can be easily parsed and reconstituted in JavaScript code. JSON is the preferred format when returning data during an Ajax call, because it’s easy for JavaScript code to reconstitute the data into JavaScript objects at the browser.
      • The Views/Home folder contains a single view named Index.cshtml. The HTML markup is straightforward enough, you’ll add JavaScript code to implement Ajax calls to invoke the Home/FilterNames action method during this lab.
      • View code file.
  5. Making an Ajax call
    • In Index.cshtml, note the following points:
    • View code file.
      • The page has a text box where the user can enter a player’s name. Each keystroke will trigger the getMatchingPlayers() JavaScript function, which is empty at the moment. You’ll implement this function in this lab, to make an Ajax call to the Web server.
      • The page also has a <ul> control named ResultList, ready to display a bulleted list of players info returned from the Web server.
    • As mentioned earlier, you’re going to use Jquery to simplify Ajax interactions. ASP.NET MVC projects automatically contain the Jquery JavaScript files see the Scripts folder in your project. Drag the appropriate script files into your Index.cshtml page (in the <head> section). Visual Studio should automatically add the relevant <script> tags.
    • View code file.
    • <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
      <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

      Now add code in the getMatchingPlayers() JavaScript function, to make a simple Ajax call:

      • First, display a diagnostic alert() popup to show the current text from the Name text box. This is a useful sanity check, to make sure the function is being called correctly and that it is getting the correct text from the text box.
        alert(document.getElementById('Name').value);
      • Empty the current contents of the ResultList control (you can use the jQuery empty() function to do this). This ensures that the list of matching names is emptied (and then re-populated) on every keystroke.
        $("#ResultList").empty();
      • Make an Ajax call via $.ajax({ …}), where the … represents a series of configuration options for the Ajax call. Replace the … with the following options for now:
        $.ajax({
             type: "GET",
             url: "/Home/FilterNames",
             data: { filter: $("#Name").val() },
      • These configuration options represent an HTTP GET request to the URL /Home/FilterNames. This will cause the Web server to invoke the FilterNames() action method in the HomeController class. This method requires a parameter named filter, and this is supplied via the data: { filter: $(“#Name”).val() } option
      • After the Ajax call, display another diagnostic alert() popup just to confirm that the Ajax call was issued successfully (we’ll show how to handle the returned data shortly).
        alert("Success");
    • Run the Web application. In the text box, type a letter. Verify that a pair of alert() popups appear, showing that the keystroke was detected and that the Ajax call was issued successfully.

Lab 2: jQuery and Ajax

Lab 2: jQuery and Ajax
  1. Overview
    • Jquery has excellent support for Ajax
      • Jquery provides functions that make it easy to invoke server-side functionality in an Ajaxified manner
      • Supports HTTP GET and HTTP POST requests
      • Supports JSON format for data passed back and fore
  2. Making an Ajax Request
    • To make an Ajax HTTP request to a Web server URL – Can also be $.post:
      $.get( url,
          [ data ],
          [ success(data, textStatus, jQueryXMlHttpRequestObject) ],
          [ dataType ] )
    • url
      • A string containing the URL to which the request is sent
    • data
      • A map or string that is sent to the server with the request
    • success(data,textStatus,jQueryXMlHttpRequestObject)
      • A call-back function that is executed if the request succeeds
    • dataType
      • The type of data expected from the server
      • The default is “intelligent guess” (xml, json, script, or html)
  3. Additional Possibilities
    • Generalized Ajax call:
      $.ajax({
        type:  "GET",
        url:  "url",
        data:  somedata,
        success: callback
      });
    • Load content:
      $.load(url, [data], [callback]);
    • Example: See UseAjaxWithJQuery.cshtml
    • View code file.
Lab
  1. Processing the Ajax response
    • The Ajax call you implemented in lab one causes the Web server to invoke the FilterNames() action method in the HomeController class. As we mentioned earlier, this method returns this data as a JSON result. To see what JSON data looks like, run your Web application again, and then modify the address in the browser address as follows (your port number may be different):
      https://localhost:50351/Home/FilterNames?filter=y
    • This will call the FilterNames() method, which will return a collection of Player objects whose name contains “y” somewhere. The data is returned in JSON format, which looks like this in the browser window:
      T15P5
    • This is regular JavaScript object syntax for a collection of objects:
      • The enclosing [] means JavaScript array.
      • Each item in the array is enclosed in {}, which means JavaScript object.
      • Inside each {} is a set of 3 propertyName:propertyValue pairs, to represent the FirstName, LastName, and Salary properties of each player.
    • Now that you understand the format of the data returned from the Web server, you can enhance your Ajax call to handle the returned data. Follow these steps:
      • In Visual Studio, re-open Index.cshtml and locate the code that makes the Ajax call.
      • View code file.
      • In the $.ajax({…}) call, set the success property to a call-back function as follows (this is obviously a simplified approach for now, but it’s worthwhile working in baby steps with Ajax to make sure each step is working):
        success: function (data) {
         alert("Data received: "+ data);
        }
    • Run the Web application again. In the text box, type in a letter. Verify that you get an alert() popup such as the following, which verifies you’ve received an array of objects from the Web server:
      T15P6
    • Now enhance the success function so that it processes the data parameter properly. Bearing in mind that the data parameter is an array of player objects, here are some additional hints:
      • Use the Jquery $.each() mechanism to process each item in the array.
      • For each item, invoke a function to process it. The function should take two parameters (key and value). The key is the array index, and the value is the actual player object.
        $.each(data, function (key, val) {...}
      • The function should get the ResultList bulleted list and append an <li> element. The <li> element should display the FirstName, LastName, and Salary properties of the player object.
        $('#ResultList').append("<li>" + val.FirstName + " " + val.LastName + " [$" + val.Salary + "]</li>");
    • Run the Web application. In the text box, type in a letter. Verify that the Web page displays a list of matching players. For example:
      T15P7

 

Well done. You have completed the tutorial in the HTML5/CSS3/JS course. The next tutorial is

16. Web Sockets


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top