1 designing & developing web- based solutions in asp.net week 6 javascript & ajax
TRANSCRIPT
1
Designing & Developing Web-Based Solutions in ASP.NET
Week 6
JavaScript & AJAX
Today’s Agenda
JavaScript Language Overview What, Why, Where, When, How
AJAX & ASP.NET AJAX Callbacks Comparison AJAX Web Services AJAX Controls
Lab: Play with JavaScript Build AJAX Web Services in different ways
Designing & Developing Web-Based Solutions in ASP.NET 2
What is JavaScript?
Java == JavaScript?NO!!!
Original Name = ECMAScript European Computer Manufacturers Association
Created by Netscape
First used in 1996 (Netscape & IE)
Designing & Developing Web-Based Solutions in ASP.NET 3
Why JavaScript?
Read / Write HTML in browser
React to events
Client side validation
Read / Write cookies
Detect Browser
Designing & Developing Web-Based Solutions in ASP.NET 4
JavaScript – Placement
Embedded anywhere within < html ></html> Attribute to an HTML tag:
<body onunload="alert('Thanks for visiting');"> In a <script> tag (unlimited tags)
Executed on load:
<script>alert(‘Greetings');</script> Executed when function called:
<script>function Greet { alert(‘Greetings') ;}</script>
Download a .js script file from a server:<script type="text/javascript" src=“URL/MyScript.js"></script>
Designing & Developing Web-Based Solutions in ASP.NET 5
JavaScript – Order of Execution
Top to Bottom of page Caution:
“Execute in Place” script must occur after elements it modifies.
Designing & Developing Web-Based Solutions in ASP.NET 6
JavaScript - Compatibility
Comments hide script for non-java browsers
<script type=“text/javascript”><!- -
Window.alert(‘This browser supports JS’);
// - - >
</script> Other comment styles, same as C
/* code block */ // single line
Designing & Developing Web-Based Solutions in ASP.NET 7
JS – Language Basics
Case Sensitive Memory Managed 16 bit Unicode strings
Designing & Developing Web-Based Solutions in ASP.NET 8
JS - Variables
Generic Type “var” var mytext = ‘some text’; var x = 5; var myObj = new XmlHttpRequest();
Specific Types int, float, byte, double, char, short, boolean More…
Auto Declaration if not previous defined y = 10;
Redefinition does not clear var x; // still equals 5
Designing & Developing Web-Based Solutions in ASP.NET 9
JS – Variable Scope
Global to page (page shares all script space)<script id=“block1”> var a=1; </script>
<script id=“block2”> var b=2; </script>
<script id=“block3”> var c=a+b; </script>
Local to functionfunction First() { var x=1; }
function Second() { var y=2; }
function Third() { var z= x+y; } // SCOPE ERROR
No Block Scope { {var inSecondBlock = 1;}
Designing & Developing Web-Based Solutions in ASP.NET 10
JS - Arrays
Yes, but not really. More like a Vector ADT Automatically increases in size Mixed type elements
var myArray = [ ‘mystring’, 5, null, 1.8, true ] Single dimension, but can have arrays of arrays
var two_d = [ [ 1, 2, 3], [4, 5, 6] ]; two_d[1][1] // === 5
Designing & Developing Web-Based Solutions in ASP.NET 11
JS - Objects
No class definition, only Object Literals var person = {
ssn: 555123333,
name: {
first: “Joe”,
last: “Cool”
} };
Retrival person.name.first person[“ssn”]
Designing & Developing Web-Based Solutions in ASP.NET 12
JS - Objects
Augmentationperson.address = “1234 Mocking Bird Lane”; person object augmented with “address” property.
Deletedelete person.ssn; “ssn” property removed from object.
Passed by Reference Never copied
Designing & Developing Web-Based Solutions in ASP.NET 13
JS – Comparison, == vs ===
== // is equal to === // value and type equal
Given that z=3;
z == 3 // true
z == “3” // true
z === 3 // true
z === “3” // false
Designing & Developing Web-Based Solutions in ASP.NET 14
JS – Popup’s
alert(“hello world”);
var result = confirm(“Press OK or Cancel”);
var result = prompt(“How old are you?”, “Enter age”);
Designing & Developing Web-Based Solutions in ASP.NET 15
JavaScript – Common Events
Event Trigger
onchange Change check/radio or leave textbox
onclick, ondblclick Click on button or in area
onmouseover, onmouseout Mouse enter/exit region
onkeyup, onkeydown Keypress within focused control
onselect Text selection
onfocus, onblur Control receives/loses input focus
onabort, onerror Image download canceled/errored
onload Page completely downloaded
onunload Before new page downloaded
Designing & Developing Web-Based Solutions in ASP.NET 16
DOM and DHTML
Interact with web page as tree of xml objects DHTML = “Dynamic HTML” JavaScript + DOM
The Document Objectvar label = document.getElementById(“LabelOne”);
label.innerText = “text changed in script”;
Designing & Developing Web-Based Solutions in ASP.NET 17
DOM - Object PropertiesMethod Description Sample
innerHTML HTML between begin & end tags
label.innerHTML = “some text”;// OUTPUT<div>some text</div>
style CSS properties Label.style.fontSize = “10”;
value Controls value attribute
Label.value = “set the text”;Checkbox.value = “true”;
tagName HTML tag name myDiv.tagName == “Div”
parentElement Parent Object Var myDiv = label.parentElementmyDiv.style.backgroundColor = “blue”;
Designing & Developing Web-Based Solutions in ASP.NET 18
document.* Collections
document.anchors[] document.images[] document.links[]
Designing & Developing Web-Based Solutions in ASP.NET 19
document.* Properties
cookie domain lastModified readyState referrer title URL
Designing & Developing Web-Based Solutions in ASP.NET 20
document.* Methods
close() getElementById() getLementsByName() getElementsByTagName() open() write() writeln()
Designing & Developing Web-Based Solutions in ASP.NET 21
Browser DOM Objects
Window // open browser window info History // Sites Visted Location // Current URL info
Navigator // Browser Info Screen // Display mode info
Designing & Developing Web-Based Solutions in ASP.NET 22
HTML DOM Objects
Document // The currently loaded HTML Anchor Button Image Body Form Table one fore each element type…
Designing & Developing Web-Based Solutions in ASP.NET 23
JavaScript – Reference
Good Reference & Samples sites www.W3Schools.com Microsoft – MSDN CodeProject
DOM http://www.w3schools.com/HTMLDOM/dom_reference.asp
JavaScript http://www.w3schools.com/jsref/default.asp
Designing & Developing Web-Based Solutions in ASP.NET 24
Lab – CodeProject Samples
Vote
Paint
Designing & Developing Web-Based Solutions in ASP.NET 25
26
Designing & Developing Web-Based Solutions in ASP.NET
AJAX
AJAX - Introduction
Acronym Asynchronous JavaScript and XML Correction: Communicates a string, not always XML
Biggest Issue = Browser Compatibility
Uses JavaScript to communicate to server Does not cause a page refresh Uses DOM to update HTML of current page
Designing & Developing Web-Based Solutions in ASP.NET 27
AJAX – 2 Step Process
Request JavaScript sends request to Server
XMLHttpRequest
Response Browser routes server response to script
function myResponseFunction()
Designing & Developing Web-Based Solutions in ASP.NET 28
AJAX – XMLHttpRequest()
The cornerstone of AJAXvar req = new XMLHttpRequest(); // ActiveX for older
Set Location & protocol req.open( < GET,POST,PUT >, url)
Set JavaScript function as Callback req.onreadystatechange = myCallback;
Send request req.send()
Designing & Developing Web-Based Solutions in ASP.NET 29
AJAX – The Request
<script>
Var request; // will also use this variable in callback
function getMyData()
{ request = new XMLHttpRequest();
request.open(“GET”, “UpdateData.ashx”);
request.onreadystatechange = myCallback;
request.send();
}
</script>
Designing & Developing Web-Based Solutions in ASP.NET 30
AJAX – Server’s HTTP Handler
File APP_Code / UpdateData.ashx public class UpdateData : IHttpHandler {
public void ProcessRequest( HttpContext context) {
context.Response.Write(“Hi from the server”); }
public bool IsReusable // keep handler loaded or discard {get{ return true;}}
}
Designing & Developing Web-Based Solutions in ASP.NET 31
AJAX – The Callback
// Use original “var request;” from caller<script>
function myCallback()
{
if(request.status == 200) // check for pass/fail
{
var txt = request.responseText;
}
}
</script>
Designing & Developing Web-Based Solutions in ASP.NET 32
AJAX – HTTP Handler Setup
Described in Chapter 5 – ASP.NET Applications
Simple Approach Add .ashx file to App_Code folder Register Handler in web.config
<system.web>
<httpHandlers><add verb=“Get” // GET,PUT,POST or *
path=“UpdateData.ashx” // filename
Type=“UpdateData”> // namespace.ClassName
Designing & Developing Web-Based Solutions in ASP.NET 33
AJAX – Client Callbacks
Yet another way Server Differences
Public partial class ClientCallback : System.Web.UI.Page, ICallbackEventHandler
Doesn’t use IHttpHandler Server callback can be in page’s code-behind.cs
Client doesn’t need to call XMLHttpRequest ASP.Net handles XMLHttpRequest Must register callbacks in the servers Page_Load() JavaScript Callback now contains 2 parameters
Designing & Developing Web-Based Solutions in ASP.NET 34
AJAX –Server Callback
Server ModificationsPublic partial class ClientCallback :
System.Web.UI.Page, ICallbackEventHandler
{Public void Page_Load(…)
{
String myScriptcallback =Page.ClientScript.GetCallbackEventReference(
This, “document.getElementById(‘myLable’).value,
clientUpdateDataCB, “null”, true);
myLabel.Attributes[“onchange”] = myScriptcallback;
}
}Designing & Developing Web-Based Solutions in ASP.NET 35
AJAX – Client Changes
Callback has parameters Doesn’t use the XMLHttpRequest
function clientUpdateDataCB(result, context)
{var text = result;
Window.alert(text);
}
Designing & Developing Web-Based Solutions in ASP.NET 36
37
Designing & Developing Web-Based Solutions in ASP.NET
ASP.NET AJAX
(Formerly Known as “Atlas”)
ASP.NET AJAX – Comparison
Simplified client-server communication Uses WebService protocol. Handles data serialization (no more “all data in a string”)
Typed data Server send client typed data JavaScript extensions add Object Oriented features to script.
Premade AJAX Tools Extensions (UpdatePanel, Timer, Update Progress) Toolkit
Controls Control Extenders
Designing & Developing Web-Based Solutions in ASP.NET 38
AJAX – Creating Web Service
Add new item Web Service Creates
Current folder: MyWebService.asmx App_Code folder: MyWebService.cs
Designing & Developing Web-Based Solutions in ASP.NET 39
AJAX – Web Service (.asmx)
.asmx locates the code page .cs contains the actual Web Service
[WebService(Namespace = "http://tempuri.org/")] // Uncomment for AJAX “JSON” service // [System.Web.Script.Services.ScriptService] public class AJAXWebService : WebService {
[WebMethod] public string HelloWorld() { return "Hello World“; }
}
Designing & Developing Web-Based Solutions in ASP.NET 40
AJAX – Client Setup
Add new item AJAX web form Creates normal web form in current directory:
WebPage.cs WebPage.aspx
Automatically Adds: <asp:ScriptManager />
OR
Add new item Web form Then manually add <asp:ScriptManager> to .aspx
Designing & Developing Web-Based Solutions in ASP.NET 41
AJAX – ScriptManager
Add web service reference Must live inside <form>
<form><asp:ScriptManager ID=“ScriptMgr" runat="server“>
<Services><asp:ServiceReference
Path="~/Projects/Samples/…/AJAXWebService.asmx" />
</Services>
</asp:ScriptManager> </form>
Designing & Developing Web-Based Solutions in ASP.NET 42
AJAX – The Client Call
Add a control to page Add callback to control
JavaScript function call <asp:input … onclick=“LocalCallHelloWorld();“/>
or Embedded JavaScript
<asp:input … onclick=
“AJAXWebService.HelloWorld(OnResponse, OnErr);“/>
Designing & Developing Web-Based Solutions in ASP.NET 43
AJAX – In Page Web Service
<ScriptManager EnablePageMethods=“true”>
public partial class AJAXWebService : Page {
[WebMethod()]
[ScriptMethod()]
Public static HelloWorld(){ return “Hello World”}}
PageMethods.HelloWorld(OnResponse, OnErr);
Designing & Developing Web-Based Solutions in ASP.NET 44
<asp:Button> - Special Case
<asp:Button onclick=“ServerOnlyMethod"> onclick attribute defined by <asp:Button>
Normally JavaScript Events pass-through (onblur, onclick,…)
Alternative OnClientClick=“SomeJavaScript()” Also does postback Work Around
<asp:Button OnClientClick=“return MyFunc();” />
function MyFunc{ … return false;}
Designing & Developing Web-Based Solutions in ASP.NET 45
AJAX – UpdatePanel
Must use <asp:ScriptManager> Updates all UpdatePanels
Ignores controls not in an update panel Set UpdateMode=“Conditional” to NOT update all
panels.
<asp:UpdatePanel> <ContentTemplate>
<asp:Label/> …
Designing & Developing Web-Based Solutions in ASP.NET 46
AJAX – UpdatePanel Triggers
Triggers Allow
Controls outside UpdatePanel to cause update
Inner controls to cause conditional updates.
Designing & Developing Web-Based Solutions in ASP.NET 47
Next Week
Another callback mechanism WCF web service (MS preferred way)
Another DOM parser for JavaScript jQuery
More premade AJAX controls AJAX Toolkit
Designing & Developing Web-Based Solutions in ASP.NET 48
Lab – ASP.NET AJAX
Build a Web Service Button Sample Convert to PageMethod
Use an UpdatePanel
Designing & Developing Web-Based Solutions in ASP.NET 49