Ajax .il



Hadassah Academic CollegeAjaxInternet Programming CourseDr Solange KarsentyUpdated 13/12/18The need for interactive contentSome facts:HTML and HTTP are non-interactive and require coarse grained updates (every request produces a new HTML document).Browsers have become the “desktop”: users perform all tasks though the browser, computing, games, utils, etc. Websites do not require installation and updates!Websites need to provide interactive content (historically Flash and Applets have failed) and advanced user interaction (graphics, animation, drag and drop, reactive elements etc).Traditional websites perform infrequent large updates:The user visits a page, then clicks on a link or submit a form, then gets directed to a new document. This model of interaction based on “navigating” in a graph of pages can be slow and confusing. We would like to perform frequent and small updates, without reloading a new document. This allows the user to stay in the context of the document and keep focused on the task, interacting with the various page elements, thus the name “rich internet application applications” vs. websites.In this case the page executes small updates give the feel of an “application” since the user does not leave the current URL. The user interaction is data and event driven instead of page-driven. This is what Ajax is about.What is AjaxAjax stands for Asynchronous JavaScript and XML (today XML is replaced by JSON which is a more compact format). It is a technology independent from the browser. In order to learn Ajax, one needs to know Javascript, HTTP, CSS, JSON and DOM manipulations. The most classical example of Ajax is the autocomplete functionality is search forms (see the figure below). For example, Google search produces a list of suggested search words as soon as the user starts typing. This list is done by an Ajax call. In traditional forms, you fill out a form, hit submit, and get directed to a new page with results from the server. Ajax does not redirect the user to a new page, it allows processing a form as soon as the user starts typing. Ajax performs an asynchronous request, which means it will not block any user interaction on the page while performing the request and processing the result. In the figure below, the search results are displayed immediately (autocomplete) below the input text.Technically Ajax allows to:Update a web page without reloading the page (creating different screens for user interaction)Request data from a server - after the page has loaded (for example to retrieve a list of words for autocomplete fields)Receive data from a server - after the page has loaded (for example to display live data about stock prices).Send data to a server - in the background (for example to process/submit a form without leaving the page).Conceptually, Ajax allows us to build web applications: it means we can build a single page (one URL) for the website and using Ajax and javascript we can modify the content of the page and generate the various “pages” without leaving the URL. The browser loads only one page and all interaction and state changes happen inside Javascript and the DOM. Such websites are sometimes confusing: the user sees different pages, clicks on “back” of the browser and suddenly exits completely the website while they meant to go to previous screen. Therefore, the navigation hints (buttons etc) must be very clearly displayed inside the page.When to use/not to use Ajax?Very often a web application is meant to be a self-contained workspace: the environment, variables, functions are maintaining a global state to generate the various “pages” (or states). Some of the data is to be retrieved on the server side, and Ajax is the solution to communicate with the server without losing current context.If a webpage contains a link (<a href ..) the browser normally performs a new http request and all of the current page scope is unloaded (disappears). In the same way, the regular submit event of a form (see the section about forms) will redirect the browser to a new URL.Ajax can prevent this: with Ajax calls, you can avoid unnecessary loading time, give a more responsive experience to the user, and most of all: keep your JavaScript state and environment. Assume for example that you have an online shopping website, the shopping cart is updated locally as some variable in your code, if you redirect the user to a new URL, this variable will disappear from the scope (a new scope will be created). As a result you will need to store the shopping cart elsewhere (usually session or cookies) and retrieve it from other pages. Tips on web design related to AjaxYou should identify the main blocks of your website: for example registration, store, payment etc… It is recommended to divide these into different web pages and inside each of them to perform Ajax requests to maintain a “web app” style of interaction. For example the user experience in a shopping website is much better when the user stays in context and data is updated on a single page.Since a web app can easily grow, you have to be careful not to have very big pages (lots of javascript, slow loading/execution time), so you need to find a good balance to provide an easy to maintain structure and a good user experience.The basic Ajax processNote that we first show examples is pure Javascript code for Ajax, but in this course we will use only jQuery code (see section 4).To perform an Ajax request, one must write Javascript code and HTML elements to display the results. Here is a Javascript/HTML example with a button that modifies a title element content with some data retrieved from the server via a HTTP request. The HTTP request loads a file (“newtitle.txt”) from the server to replace the title (usually, it loads a database request instead of grabbing a static text file). Also, note that we will later use jQuery syntax which is a lot more compact than such example. Here is the pure javascript code:<script>function loadTitle() { var xhttp = new XMLHttpRequest(); //(1) xhttp.onreadystatechange = function() { // (2b) if (this.readyState == 4 && this.status == 200) { // (3a) document.getElementById("demo").innerHTML = this.responseText; // (3b,3c) } }; xhttp.open("GET", "newtitle.txt", true); // (2c) xhttp.send(); // (2d)}</script><div?id="demo">??<h2>this title is going to be modified by clicking on the button below</h2>??<button?type="button"?onclick="loadTitle()">Change Title</button></div>Let’s look closely at the Javascript code.It defines an object for sending HTTP requests (1)It initiates the requestGet request object (1)Designate an anonymous function/response handler function (2b)Supply as onreadystatechange attribute of request Initiate a GET or POST request (2c)Send data (2d)Handle responseWait for readyState of 4 and HTTP status of 200 (3a)Extract return text with responseText or responseXML (3b)Do something with result (3c)Let’s look closely at the HTML code.It loads the JavaScriptIt designates an element that initiates request (the button)It gives and id to an output placeholder region (“demo”)Here are the properties of the XMLHttpRequest Object:PropertyDescriptiononreadystatechangeDefines a function to be called when the readyState property changesreadyStateHolds the status of the XMLHttpRequest.0: request not initialized?1: server connection established2: request received?3: processing request?4: request finished and response is ready?responseTextReturns the response data as a stringresponseXMLReturns the response data as XML datastatusReturns the status-number of a request200: "OK"403: "Forbidden"404: "Not Found"statusTextReturns the status-text (e.g. "OK" or "Not Found")GET or POST?GET is a type of request of the http protocol where parameters (Ajax data or HTML form input elements) are sent by within the URL, for example: pass to the program register.php the parameters firstname and lastname with their respective values josh and bush.Some important aspects of GET requests:GET requests can be cachedGET requests remain in the browser historyGET requests can be bookmarked (data visible to the user)GET requests should never be used when dealing with sensitive dataGET requests have length restrictionsGET requests should be used only to retrieve dataPOST on the other hand will hide the data within the HTTP body part of the request. Therefore, it should be used for dealing with sensitive data.More aspects of POST requests:POST requests are never cachedPOST requests do not remain in the browser historyPOST requests cannot be bookmarkedPOST requests have no restrictions on data lengthGET is simpler and faster than POST, and can be used in most cases.However, always use POST requests when:You need to send sensitive dataA cached file is not an option (update a file or database on the server).Sending a large amount of data to the server (POST has no size limitations).Sending user input (which can contain unknown characters), POST is more robust and secure than GET.You don’t want the user to be able and create a bookmark of your requestMore details on the difference between the two.An autocomplete exampleThe following example will produce a list of suggested word according to the user input in a text field (you can run such example here). For example typing the letter “a” will display:Assuming you have a Servlet “SearchServlet” that receives a parameter “q” that will search a for completion in a database, you would write the following code:<html><head><script>function?showHint(str) {????if?(str.length?==?0) {???????? document.getElementById("txtHint").innerHTML?=?"";????????return;??? }?else?{??? ????var?xmlhttp =?new?XMLHttpRequest();??? ??? xmlhttp.onreadystatechange?=?function()?{????????????if?(this.readyState?==?4?&&?this.status?==?200) {?????????????document.getElementById("txtHint").innerHTML?=?this.responseText;??? ????????}??????? };??? ??? xmlhttp.open("GET",?"SearchServlet?q="?+ str,?true);??????? xmlhttp.send();????}}</script></head><body><p><b>Start typing a name in the input field below:</b></p><form>?First name:?<input?type="text"?onkeyup="showHint(this.value)"></form><p>Suggestions:?<span?id="txtHint"></span></p></body></html>Notice the HTML elements: there is a placeholder id="txtHint" to insert the result of the Ajax response. This is where the list of suggested word is inserted. The user input next has a function bound to the keyup event (not keydown!), which means the function will be called after each keystroke release of the user, as of first character. This type of event can be used for example to validate input in a form. Usually validation is triggered only after a minimum number of characters have been entered, otherwise it can be very disturbing for the user. The writing of Ajax code in Javascript is much cleaner and easier in jQuery. In this course we exclusively use jQuery.Ajax with jQueryAjax call in jQuery can easily be defined in various ways:$.get(URL,callback);$.post(URL,data,callback);// here is the more general function$.ajax({????????url : formURL,????????type: "POST", // POST or GET????????data : postData, // the form data????????success:function(data, textStatus, jqXHR) ????????{????????????//data: return data from server????????},????????error: function(jqXHR, textStatus, errorThrown) ????????{????????????//if request fails????? ????????}????}For example, here is an Ajax call to retrieve the city name, given a zipcode entered in a HTML element with id “zip”. The Ajax called is triggered by a button click:$("button").on("click", function(){??? $.post("getCityByZipcode.php",// name of server side component??? { // sending POST parameters with the http request // get the zip code from an input element??????? zipcode:?$("#zip").val(),??? },????function(data, status){??????? alert("Data: "?+ data +?"\nStatus: "?+ status); // display response??? });});Ajax and FormsForms are the most basic elements for building user interfaces. <form?id="userform” action="/SomeServlet" method="get" >? First name:<br>??<input?type="text"?name="firstname"><br>? Last name:<br>??<input?type="text"?name="lastname"><br>??<input?type="submit"?value="Submit"></form>A form contains various input elements and a submit button to process the form. The action attributes defines the server side component (for example a Servlet) that will process the request. After submission the user is redirected to a new document (a new page is loaded).Ajax calls can easily be attached to the form elements and to the submit button as well. When attaching an Ajax call to the submit event, the ACTION element of the form is irrelevant since an Ajax call will submit the form asynchronously to the server. This prevents the redirection to a new URL, instead the Ajax http request will process the form.When using Ajax, you create your own HTTP request and among other things you need to pass the form data. This is why jQuery provides useful function such .serialize() as turning a form data into a query string for a GET request:$("#userform" ).serialize();produces a string like this: firtname=Ben&lastname=DavidThe .serialize() method serializes a form's data into a query string. For the element's value to be serialized, it must have a name attribute. Note that values from inputs with a type of checkbox or radio are included only if they are checked.jQuery also provides a .serializeArray() function to encode a set of form elements as an array of names and values.Form validation and submissionFor submission is usually automatically handled via the ACTION attribute of the form and the SUBMIT button: if you don’t attach any Javascript code to the submit event, the browser will send all form data to the server (ACTION value), and it will return a new page (whatever the ACTION is, it will be the new URL). The user will be redirected to a new URL. However, if we use Ajax to submit the form, we can handle the response of the server within the page and avoid jumping to a new URL.Here is an example of form validation and submission via Ajax. The jQuery code attaches to the submit event and anonymous function that checks first that input is non empty, then submits the form via an Ajax call. Again the advantage of an Ajax submit is that the user is not redirected to a new page, the result of submit is processed locally on the page and displayed within the page.Assume you have a form:<form?id="userform” action="/SomeServlet">? First name:<br>??<input?type="text"?name="firstname" class="required"><br>? Last name:<br>??<input?type="text"?name="lastname" class="required"><br>??<input?type="submit"?value="Submit"></form>Note that we define a class “required” on elements we need to validate as non empty before submission, this way we perform validation on such element with a single selector.// Using validation to check for the presence of an input$("#userform").submit(function(event) { // If .required's value's length is zero if ( $(".required").val().length === 0 ) { // Usually show some kind of error message here // Prevent the form from submitting event.preventDefault(); } else { // send the form to the server for processing // usug $.ajax() var formURL = $(this).attr("action");// convert all form data into an arrayvar postData = $(this).serializeArray(); $.ajax(????{????????url : formURL,????????type: "POST",????????data : postData,????????success:function(data, textStatus, jqXHR) ????????{????????????//data: return data from server????????},????????error: function(jqXHR, textStatus, errorThrown) ????????{????????????//if fails????? ????????}????});event.preventDefault(); //STOP default actionevent.unbind(); //unbind to avoid multiple form submit.}});In general form validation requires a lot of string manipulations. It is recommended to use some advanced library such as . There are numerous jQuery plugins that enhance the jQuery library.7.Sending dataThere are several options for sending data with Ajax:Sending a string which is in a format “param1=value2&param2=value&….”Sending an object ( param1: “value1”, param2” “value2”, …}Sending all of form input with the serialize() functionAdditionally one can perform a very quick and simple Ajax call with the load() function. Assuming we want to perform a call to some URL and insert the result in a div, we could write something like this:$("#mydiv").load("someURL", $("#myform").serialize());Detailed examples are available in the course material.JSONJSON is a JavaScript Object Notation, in other words a format for storing and exchanging Javascript data. Typically, when building an Ajax request, you need to pass data to the server and parse a response. The JSON format is preferred because it is compact and readable. Also, all programming languages have functions to process this format. JSON is very similar to Javascript object syntax, notice the major difference: the quotes around the property names.var?myObj =?{"name":"John",?"age":31,?"city":"New York"}; // JS objectvar?person =?JSON.stringify(myObj); // convert from Object to JSONvar?myObj =?JSON.parse(person); // convert from JSON to ObjectIn the example above, myObj is transformed into JSON format which can be easily processed via an Ajax call.Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript. The JSON format must use double quotes:{?"name":"John"?}while in Javascript it is written as:{ name:"John"?}A JSON object can be modified in both ways:person.name?=?"Gilbert";person["name"] =?"Gilbert";When you develop server side components for Ajax calls (for example Servlets or JSP), you make sure to generate output in JSON format, so that parsing the result from Javascript becomes easy (JSON.parse() converts the result in an JS object). jQuery offers a builtin Ajax call (.getJSON()) to automaticall parse a JSON response.ReferencesSlides: : ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download