Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to. Learning Objectives By the end of this lecture, you should be able to: – Describe the difference between client-side and server-side.

Similar presentations


Presentation on theme: "Introduction to. Learning Objectives By the end of this lecture, you should be able to: – Describe the difference between client-side and server-side."— Presentation transcript:

1 Introduction to

2 Learning Objectives By the end of this lecture, you should be able to: – Describe the difference between client-side and server-side scripting – Name some commonly encountered web-based tasks that can only be achieved using server-side scripting – Describe the benefits of using AJAX – Contrast the AJAX request-response model with the traditional request- response model – Describe the 3 types of server applications needed to run most commercial or large-scale web sites

3 What Isn’t AJAX? Admittedly, this is a strange way to introduce a topic. However, there is some confusion about what AJAX is and is not. So let’s start with what it isn’t: AJAX tands for ‘Asynchronous JavaScript And XML’ – yet this acronym is not altogether appropriate. For example the ‘XML’ part of AJAX is really no longer used very much at all. AJAX is not a programming or scripting language! It certainly involves and requires scripting, but scripting is only one part of AJAX. AJAX is not a new ‘gee-whiz’ technology. In fact, it is really a collection of relatively “older”, but well- established and stable technologies.

4 Introduction: Okay, so what is AJAX? AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, must often reload the entire page if a new piece of information is being requested from the server. Pretty important nowadays. In fact, AJAX is used on many, many sites that you probably use on a daily basis. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

5 Client Side v.s. Server Side Scripting – The Client All of the scripting we have done to date is “client-side” scripting. Client-side script = script that is executed by the client (e.g. your web browser). Most popular client-side scripting language is JavaScript (and the jQuery dialect). Main advantage to client-side scripting is that it is faster, and distributes the workload. Example: Imagine even a very simple script that does a conversion from pounds to kilograms. On a single client, this is extremely rapid. But imagine if this same script was executed on a server that receives 1000 requests per minute. Many such pages could bog down a web server. – Much better to distribute this workload to the clients

6 Client Side v.s. Server Side Scripting – The Server Sometimes the requested information/resource simply can not be processed by the client A server-side script is a script that is stored on and executed by the web server. Most popular server-side scripting language today is probably PHP – Others include ASP.NET ColdFusion Ruby Python Many others Example – Amazon.com: – Request information about a product – Requires a database lookup – Convert the user's text field input into a database query (client or server side script) – Query the database (must be server side)

7 Scenarios that typically require server-side scripts Sending an email with information from a form Accessing any file that resides on the server such as a database, spreadsheet, other HTML files, text documents, etc. One of the most common reasons for using server-side scripting is when you want to give the user the ability to access some specific pieces of information on a resource located on the server (e.g. querying a database) but without giving them the ability to see the entire file/resource. AJAX requires server-side scripting as we will see.

8 AJAX and jQuery Characteristics of AJAX include: – Somewhat involved in terms of code length and complexity – Several steps involved - even in basic programs – Prone to cross-browser compatibility issues AJAX is scripted using JavaScript. (In fact, JavaScript is the ‘J’ in AJAX), though the JS code is at times a bit unwieldy. jQuery greatly simplifies the length, and steps. It also handles the large majority (though not all) of browser compatibility issues. In fact, one of the reasons that jQuery became so popular was its ability to greatly simplify the use of AJAX. Other JS/AJAX libraries available besides jQuery: – DOJO – MochiKit (specializes in manipulating JSON data) – YUI (Yahoo Interface Library)

9 What does AJAX do for us? Waiting for pages to load takes time… Imagine you are viewing a company’s home page that contains numerous images, menus, buttons, icons, etc. The designer of the website intends for all of these items to be visible on every page for that company’s website. You wish to view their ‘Contact Us’ page. You click on the link to that page which has the following information: Rabbits ‘R Us Inc, 222 S. Carrot Drive, Beatrix Potter, PA, Tel: 333-444-5555 To load this contact_us.html page, you would have to wait for ALL of the site’s menus, buttons, icons, images, and so on to reload – even though much of this information is redundant It would be far faster and more efficient to have only requested the key information from the company’s ‘Contact Us’ page without having to redundantly reload all of those web page components. What if your company receives thousands of page requests a minute (or even per second)? Makes for happier customers / visitors when requests for information from your web page is visible nearly instantaneously, i.e. without having to wait for the page to reload redundant content.

10 AJAX In Action If you visit Google’s home page and begin typing a query, you will notice that as you type, the text field attempts to predict what you are searching for. Yet no other information on the page is realoded. Though you are communicating with google’s server with every character you type, much of the underlying page does not change – because it is not being reloaded. Google Maps: Allows you to zoom in/out, move in any direction and so on, without reloading any non-map areas of the page. Apple Store: Begin pricing out a new Mac, and you will see that the outer menus and so on do not change. Only the information that needs to change is requested from the server. Amazon: On most product pages, you will also see a section that says something along the lines of ‘Customers Who Bought this Item Also Bought:’. Scrolling shows a series of additional items appears on the page – yet your original product page does not change.

11 Some simple things well-suited to AJAX Browse database information: Many shopping sites will allow you to find additional/related information about a product – without leaving the product’s page. – E.g. clicking on ‘Reviews’ on Amazon.com Refresh new content at regular intervals: E.g. Visit the National Hockey League and you will see scores regularly update without the entire page refreshing. Confirmation messages: Confirm that a form was successfully submitted – without leaving the page. Voting/Rating: User clicks on stars or a poll-choice – the user’s selection can be submitted to a database on the server without leaving the page.

12 That is what AJAX Does! Makes pages feel snappier and more responsive. Enables the user to retrieve new or additional content from your website without waiting to reload the entire page. Makes for a happier customer, as well as for a happier web server (and happier IT staff, CEO, CFO, etc).

13 How Does it Work? Traditional Model Shown here is the traditional HTTP request model: 1.Web page makes a request to the server for some information (e.g. a separate ‘Contact Us’ web page). 2.Server sends back the desired web page. 3.Requesting other information (e.g. ‘Our Hours’ page) requires a new page to be downloaded from the server.

14 The AJAX Model Here is the AJAX way of doing things: 1.Web page requests some information (e.g. a ‘Contact Us’ web page) from the server. 2.Server sends back ONLY the required information – Typically loaded into a specific section (e.g. a ‘div’ section) of the ORIGINAL web page. 3.Requesting some other information (e.g. ‘Our Hours’ page) will again load ONLY the relevant information. To Summarize: With AJAX, the client requests only NEW information from the server. The original page is simply updated to reflect new content. Nothing else in the original page is changed.

15 Example 1.User clicks on a button in the ‘News Headlines’ section 2.Request is sent to the web server for that particular item. 3.Info returned from the server is loaded into the ‘headlines’ div section of the current document. – Remainder of the document (the header with title and logo at the top, the news headlines box, the footer section at the bottom, etc) is never modified or reloaded.

16 Amazon Search for ‘Seawing Gorilla Fin’

17 How Does it Work? -- Some Key Components The XMLHttpRequest Object: – Built into JavaScript is an ugly-sounding programming object called the XMLHttpRequest object. – A programming “tool” that allows JS to communicate with a web server and send information back and forth. Other JavaScript: – Open a line of communication with the web server – Requesting information – Process the returned information that comes back – Insert information into the appropriate location of our web page, etc. Web Server: – Receives requests from the client – Process those requests – Responds appropriately. – Example: Client requests information from a database (e.g. ‘Spaulding Basketball’). The server will search the database and will return all matching records to the client.

18 The Web Server Think of a web server as a glorified filing cabinet hosting lots of resources (HTML pages, drivers, databases, etc, etc), ready to “serve” them up upon request. Hardware or software? – Probably best thought of as software. – Recall that a web client (i.e. a browser) is simply software that can request pages from a server, parse pages that come back form a server, run JavaScript, display HTML and so on. – A web server is also software, but it is entirely different from web-client software. – Server software specializes in interpreting HTTP request objects that originate from a client, retrieving the requested resource, and sending that resource back to the client. However, since web server software frequently runs on a dedicated computer whose only job in life is to run the web-server software, we frequently refer to the computer itself as “the web server”. Technically, though, the web server is actually a piece of software.

19 Web Server - Hardware HARDWARE: Four Sun Fire X4200 web servers mounted together to serve a higher- traffic site. Single PC for a low-traffic site. Numerous servers at a web-hosting service.

20 World’s First Web Server Computer Note the sticker that says: DO NOT POWER DOWN!

21 Web Server Software As you can see, web server software is an entirely different animal than web client software. This is because even though they are both examples of “software”, they have entirely different jobs to do!

22 “Resources” Not every request from a server is for an HTML document. Web servers can hold any digital item and ‘serve’ these items to clients upon request. Examples: – an updated driver for your new printer – the latest episode of Big Bang Theory from the iTunes store – a database request to search for a book on amazon.com – a request from weather.com for the latest forecast in your area – a static 15-year-old ‘HTML’ document that someone wrote giving Julia Child’s recipe for Crème Brulee

23 Web Server Software: Communication Most web clients “speak” HTML, CSS, and JavaScript Because your typical web server does not need to display web documents, there is no need to have an HTML (or CSS) parsing engine built in. The web server has specialized requirements such as the ability to – query a database – serve up a files – check log-in credentials – etc, Therefore, we typically use languages that specialize in these kinds of features Common languages for server-side scripts include PHP, ASP.NET, and others.

24 What about databases? We have repeatedly referred to databases in this lecture. Databases are the backbone behind much of the information on the web. For example, every time you search for something on Amazon or any other shopping portal, you are asking the server to query a database (via a server- side script). Even resources such as a driver for your new printer, are stored and located by the server using a database somewhere. – Similarly, information relating to that driver (e.g. installation instructions) is probably linked to the driver using a database.

25 The Pieces Web Server: A web server technically speaking, refers only to the server software. Examples: Apache, Microsoft’s IIS, and Google’s GWS Sometimes refers to the computer on which the web server software is running. (e.g. “We need to reboot the server”). Database Server: Nearly every commercial web site often includes a database application. Common database server applications include MySQL and Microsoft SQL Server. Application Server: The computer hosting the web server must also be running some software that can understand the any scripting languages that are intended for use. If you think about it, your web browser’s ability to “speak” JavaScript is built into the browser software. Most web server’s do not come pre-packaged with the ability to speak all of the many different server-side scripting languages that are commonly spoken. Administrators must install an ‘application server’ that can “speak” the desired language Examples: PHP, ASP.NET, ColdFusion, etc. (May, 2010)

26 Combinations Example – Commercial Setup: – Web Server: Microsoft IIS – Database Server: SQL Server – Application server: Microsoft's ASP.NET Example – Freeware/Open Source Setup – Web Server: Apache web server – Database Server: My SQL – Application server: PHP – This is a particularly popular combination and is called 'AMP'

27 Running AJAX AJAX does require access to a web server that is running an application server. The ‘studentweb’ web server at CDM runs PHP and a couple of other application server software apps. In order to work with your AJAX programs, you will have to upload your documents every time you make a change! (You will quickly find that this is a tedious step.) Option: You can install AMP on your own computer as a "development server" When everything is ready to go, you can upload to the web server. For this course, we will only be dipping our toe into running AJAX, so you probably do NOT need to bother setting up a development server AMP.

28 Installing AMP It can be somewhat time-consuming to set up and configure AMP. If you are interested in really getting in there and learning PHP, then installing AMP is probably a great idea. There are some installers out there that install all three components with only one executable. One of the current favorites is WampServer: Windows: ‘WAMP’ at http://www.wampserver.com/en/http://www.wampserver.com/en/ – Video installation guide: http://uptospeedguides.com/wamp/http://uptospeedguides.com/wamp/ Mac: ‘MAMP’ at http://www.mamp.info/enhttp://www.mamp.info/en – Video installation guide: http://uptospeedguides.com/mamp/http://uptospeedguides.com/mamp/

29 Ajax - Part II Communicating with the Server

30 Learning Objectives By the end of this lecture, you should be able to: – Describe the overview of steps involved in communicating with the web server for an AJAX cycle – Describe what is meant by a ‘callback’ function – List and define some of the more common ‘status response’ messages that come from a server – Describe what is meant by the ‘A’ in AJAX – Describe the kinds of tasks typically handled by a server-side script

31 Steps in communicating with the web server There are a few steps involved in setting up an AJAX communication with the server. Here is the overview: Obtain a copy of the ‘ XMLHttpRequest object’. Use this object to specify the kind of data you are going to send and where the data should go. Write a “callback” function to handle whatever information is received back from the browser (e.g. part of an HTML file, a query result from a database, etc) and update the web page. Send the request to the server. Examine the response from the server for other relevant data. The main point of Ajax is to let JavaScript talk to and get information from the server. Most of the time, that means there’s another script running on the web server that completes tasks JavaScript can’t do, like reading information from a database, sending off an email, or logging a user in.

32 1: Obtain a copy of the ‘ XMLHttpRequest object’. We will use this object to make our connection to the web server and to pass information back and forth between the web server and the web client. Because the name is such a mouthful, most programmers refer to XMLHttpRequest object simply as the ‘XHR’ In JS, the code to obtain a copy of this object is: var newXHR = new XMLHttpRequest(); This step and the XHR object is one of those situations rife with opportunity for cross- browser compatibility issues. This is one of those cases where a library such as jQuery can really come to the rescue…

33 A brief aside: Not much ‘XML’ going on… In spite of the name, XMLHttpRequest there is not much XML that gets sent to or received from the server. At one point, XML was the ‘hot’ markup language – some said it was going to replace HTML as the web markup language of choice. In recent years, however, other tools have emerged to fill the void and while XML does have its uses, and is still very much around, it is not used nearly as widely as other standards. Therefore, while we will not be using the XMLHttpRequest object to work with XML, the object is still extremely helpful to web programmers as it has lots of functionality built in to it for communications with the server. From W3 Schools

34 2: Specify the kind of data to send, where to send it newXHR.open('GET', 'books.php?isbn=22233344&author=Angelou'); We invoke a function called open() to: – Specify the method used to send data (‘ POST ’ or ‘ GET ’) – Specify the file to connect to (e.g. books.php ) – Often, we append to the URL, the data that we wish to send to the server (e.g. isbn=22233344 ) IMPORTANT: The file that is specified in the open() method MUST be on the same web server as the file from which the request is originating. In other words, you can’t place your file on a DePaul web server and try to make a connection on Amazon’s web server. This is done for security reasons.

35 3. Create a “callback” function to handle the results After processing the request that has come in from the client, the server will typically respond in some way: – Output the results of a database query (e.g. the results of searching for authors with last name of ‘Rowling’) – Confirmation that a form was successfully processed ‘Thanks for joining our mailing list! ‘You have successfully updated your phone number.’ etc Your callback function should process the results that get returned from the query in some way. For example, you might take the information that came back regarding all books by an author named ‘Rowling’ and place them in a div section called ‘results’. You might format the results in an HTML list with each author in bold and the title of the book in italics, etc, etc. – Because this callback function is executed on the client, this function is nearly always written in JavaScript (or jQuery). Callback Function

36 4. Send the request At this point, we have set everything up. We now invoke the function send() which is where we “push the button” and send the request off to the server. To invoke send() we use our old friend the XHR object. There are two ways of invoking this method depending on whether we used ‘GET’ or ‘POST’ in step #2. – If we used GET, then: newXHR.send(null); – If we used POST, then: newXHR.send( query string goes here ) Recall that with POST I said that we send the information elsewhere. One place we can send it is when we invoke the send() function: newXHR.send('isbn=22233344'); As it turns out, however, jQuery also makes this step much simpler.

37 5. Receive the response Recall the callback function we created in step 3. Once the response has been received from the server, the callback function jumps into action and processes that response. The response from the server has been packaged up in a tidy little bundle and attached to the XHR object. You can use a method of the XHR object called responseText() to access this information: var responseString; responseString = newXHR.responseText(); In addition to all the ‘relevant’ information (e.g. the response of a database query), the server also bundles into the XHR object the status of the response. – We will talk about ‘status responses’ momentarily. – A competent web designer will nearly always include some code to examine the status of the response to ensure that there were no unexpected problems.

38 Completion of One Cycle That ends one iteration of the AJAX cycle. It is entirely possible, however, that there are multiple AJAX cycles going on at the same time on different parts of a single web page. We will now examine in slightly more detail, a couple of the topics from the previous steps. Refer back to the overview of these steps as we proceed. Callback Function

39 Status Response Some examples of the status response are shown here. You have almost certainly seen examples of these from time to time. 404 NOT FOUND – This means that the file requested by the client was not found. 401 UNAUTHORIZED – This means that the requested file requires authentication such as a login and password, but it was not provided. 200 OK – This response indicates that the request was processed without any problems. There are many other status responses. Your callback function could have some if/else type of code in there that springs into action in response to one or more of these responses. For example, you could write a “friendlier” version of the standard 401 error message than the standard one built into your browser.

40 Here is a somewhat typical 401 status response: Here is one that supposedly was once on the site of NY mayor MichaelBloomberg.com: Personally, I’d recommend a happy medium between these two versions. Status Response Examples

41 Simple example: Ajax Example //<![CDATA[ function loadXMLDoc() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } //]]> Let AJAX change this text Change Content See: http://www.ehmz.org/ajax/01_Ajax.html Note: To run this scrip,t you must use the URL listed here. You can not run the script from your own computer unless you have your own server and server-side script set up. Other XHR properties to be aware of include onreadystatechange, readyState, and status. We will discuss these shortly. Source code is: first_ajax.htm

42 The ‘A’ in AJAX The ‘A’ stands for ‘Asynchronous’ To explain why this is helpful, consider what the server needs to do in responding to a typical request: – Parse the incoming message – Open a connection to the database – Query the database – Form a response – Send the response to the client ‘Asynchronous’ refers to the client. It means that once your client has sent the request off to the server, the client’s script does NOT have to wait for the server’s response. Instead, this script (along with any other scripts on your page) can continue to be executed. The ability for scripts to function asynchronously can at times significantly increase the speed and efficiency of your pages.

43 GET v.s. POST These are the two commonly used methods to send and receive data between the client and the server. POST is typically used when you plan to update information on the server (e.g. add information from a ‘Join Mailing List’ form on the client to a database on the server). GET is typically used when you plan to receive information back from the user such as if you have requested information about a book on Amazon.com. With ‘GET’, the data being sent TO the server is usually appended to the end of the URL. Note in the example above, the ‘?’ after the URL, immediately after which is the info we wish to pass to the server. With ‘POST’, the data is sent separately from the URL by invoking a different function, e.g. ‘ post() ’.

44 What happens on the server? The file on the server (e.g. books.php ) will most likely contain a script that is ready to process the information that has just come in from the client. The script on the server is typically not JavaScript. These days, one of the most common and popular server-side scripting languages is PHP. – Server-side scripting languages typically specialize in things like connecting to databases, forming database queries, parsing and breaking down long strings into information, etc.

45 XMLHttpRequest Simple object with only a few methods and properties, but very functional: open() - opens the connection to a given URL setRequestheader() - adds a label/value pair to the header request send() - request is sent getAllResponseHeaders() - returns all HTTP response headers as a string getResponseHeader() - returns the specific HTTP header abort() - aborts the current request

46 XMLHttpRequest.open() HTTP method list GET - request data from the server POST - posts data to the server DELETE - deletes data for the given resource PUT - stores data for the given resource HEAD - similar to GET, but doesn't return the response body.

47 Key properties of the XMLHttpRequest Object onreadystatechange - holds a handle to the function called when the ready state of the request changes readyState - » 0 - uninitialized request » 1 - for open request » 2 - for a request that’s been sent » 3 - response received » 4 - response finished loading (this is what we look for) responseText - response as text responseXML - response as XML status - returns request status (404, 500 or 200) statusText - text associated with request status xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }

48 Simple example - Revisited: Ajax Example //<![CDATA[ function loadXMLDoc() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } //]]> Let AJAX change this text Change Content

49 Another example: ch14-02.php THIS IS THE PHP SCRIPT THAT IS STORED AND EXECUTED ON THE SERVER <?php //If no search string is passed, then we can't search if(empty($_REQUEST['state'])) { echo "No State Sent"; } else { //Remove whitespace from beginning & end of passed search. $search = trim($_REQUEST['state']); switch($search) { case "MO" : $result = " St. Louis ". " Kansas City "; break; case "WA" : $result = " Seattle ". " Spokane ". " Olympia "; break; case "CA" : $result = " San Francisco ". " Los Angeles ". " Web 2.0 City ". " BarCamp "; break; case "ID" : $result = " Boise "; break; default : $result = "No Cities Found"; break; } echo " Cities: ". $result. " "; } ?> See: http://www.ehmz.org/ajax/02_Ajax.html Note: As before, to run this script, you must use the URL listed here. You can not run the script from your own computer unless you have your own server and server-side script set up. Source code is: 02_ajax.htm PHP Script is: ch14-02.php

50 AJAX s jQuery You may have noticed that there is quite a lot of overhead (creating the XHR object, opening the connection to the server, sending the request using send(), retrieving the response using the XHR object) involved in setting up a basic AJAX cycle. All of these steps are necessary for every AJAX cycle. Yet nearly all of the “good stuff” happens inside the callback function (step #3). In addition, many of these steps are fraught with cross-browser compatibility issues. jQuery not only simplifies and shortens these steps, but it also heads off many potential cross-browser issues. You will be receiving several lectures on jQuery in the upcoming weeks.

51 Further reading –JavaScript, The Definitive Guide A "definitive" treatment of the language. Weighing in at more than 1000 pages, it performs deep dives into virtually every aspect of the language and of client-side Web apps. While the book is written as a tutorial, it need not be read from cover to cover. Rather, it's not difficult to dive into the chapter you need and extract all the information you want. In this capacity, it serves more as a detailed reference cum tutorial. –Effective JavaScript A slim volume that contains important, sometimes subtle, pointers about how the language should be used. Each pointer is given 1-2 pages of explanation that show why a recommended practice is necessary or how a proscribed practice causes trouble. –JavaScript: The Good Parts The marketing material for the title describes it as digging "…through the steaming pile of good intentions and blunders to give you a detailed look at all the genuinely elegant parts of JavaScript…". A well-known book in the JavaScript community, but a bit dense. –Pro JavaScript Performance JavaScript performance used to be a really serious problem, but the advances in the various engines and virtual machines have greatly improved responsiveness of Web apps that rely on JavaScript. This book looks at what else can be done to boost performance and focuses on tools that do all kinds of nifty tricks to boost JavaScript. –Professional JavaScript for Web Developers One person giving a list of JS books referred to is saying "… the ultimate tutorial. It takes the time to explain everything thoroughly, and it covers pretty much everything. Put aside a few hours per chapter, and by the time you're done with this one book, you'll know as much as most people who call themselves JavaScript programmers."


Download ppt "Introduction to. Learning Objectives By the end of this lecture, you should be able to: – Describe the difference between client-side and server-side."

Similar presentations


Ads by Google