490 likes | 632 Views
This resource provides an in-depth exploration of JavaScript and AJAX in the context of ASP.NET web development. Covering crucial topics such as the fundamentals of JavaScript, its implementation, and the role of AJAX in enhancing web applications, this guide is perfect for both beginners and advanced developers. Gain insights into JavaScript's syntax, execution flow, variable scope, and object manipulation, along with practical exercises to build AJAX web services. Perfect your skills in creating dynamic web pages using ASP.NET frameworks.
E N D
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
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
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
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
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
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
JS – Language Basics Case Sensitive Memory Managed 16 bit Unicode strings Designing & Developing Web-Based Solutions in ASP.NET
JS - Variables • Generic Type “var” • varmytext = ‘some text’; • var x = 5; • varmyObj = 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
JS – Variable Scope • Global to page (page shares all script space) <script id=“block1”> var a=1; </script> <script id=“block2”>varb=2; </script> <script id=“block3”>varc=a+b; </script> • Local to function function First() {var x=1; } function Second() { var y=2; } function Third() {var z= x+y; } // SCOPE ERROR • No Block Scope • { {varinSecondBlock = 1;} Designing & Developing Web-Based Solutions in ASP.NET
JS - Arrays • Yes, but not really. More like a Vector ADT • Automatically increases in size • Mixed type elements • varmyArray = [ ‘mystring’, 5, null, 1.8, true ] • Single dimension, but can have arrays of arrays • vartwo_d = [ [ 1, 2, 3], [4, 5, 6] ]; • two_d[1][1] // === 5 Designing & Developing Web-Based Solutions in ASP.NET
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
JS - Objects • Augmentation person.address = “1234 Mocking Bird Lane”; • person object augmented with “address” property. • Delete delete person.ssn; • “ssn” property removed from object. • Passed by Reference • Never copied Designing & Developing Web-Based Solutions in ASP.NET
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
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
JavaScript – Common Events Designing & Developing Web-Based Solutions in ASP.NET
DOM and DHTML • Interact with web page as tree of xml objects • DHTML = “Dynamic HTML” JavaScript + DOM • The Document Object var label = document.getElementById(“LabelOne”); label.innerText = “text changed in script”; Designing & Developing Web-Based Solutions in ASP.NET
DOM - Object Properties Designing & Developing Web-Based Solutions in ASP.NET
document.*Collections document.anchors[] document.images[] document.links[] Designing & Developing Web-Based Solutions in ASP.NET
document.* Properties cookie domain lastModified readyState referrer title URL Designing & Developing Web-Based Solutions in ASP.NET
document.* Methods close() getElementById() getLementsByName() getElementsByTagName() open() write() writeln() Designing & Developing Web-Based Solutions in ASP.NET
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
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
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
Lab – CodeProject Samples • Vote • Paint Designing & Developing Web-Based Solutions in ASP.NET
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
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
AJAX – XMLHttpRequest() • The cornerstone of AJAX varreq= 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
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
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 boolIsReusable // keep handler loaded or discard • {get{ return true;}} • } Designing & Developing Web-Based Solutions in ASP.NET
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
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
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
AJAX –Server Callback • Server Modifications Public 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
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
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
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
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
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
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
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
AJAX – In Page Web Service • <ScriptManagerEnablePageMethods=“true”> public partial class AJAXWebService : Page { [WebMethod()] [ScriptMethod()] Public staticHelloWorld(){ return “Hello World”} } • PageMethods.HelloWorld(OnResponse, OnErr); Designing & Developing Web-Based Solutions in ASP.NET
<asp:Button> - Special Case • <asp:Buttononclick=“ServerOnlyMethod"> • onclick attribute defined by <asp:Button> • Normally JavaScript Events pass-through (onblur, onclick,…) • Alternative • OnClientClick=“SomeJavaScript()” • Also does postback • Work Around <asp:ButtonOnClientClick=“returnMyFunc();” /> function MyFunc{ … return false;} Designing & Developing Web-Based Solutions in ASP.NET
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
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
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
Lab – ASP.NET AJAX • Build a Web Service • Button Sample • Convert to PageMethod • Use an UpdatePanel Designing & Developing Web-Based Solutions in ASP.NET