Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
jQuery Web Service client 1 Objective You will be able to Write JavaScript code to invoke web methods of a web service on the same server using jQuery. Use JSON (JavaScript Object Notation) for communcations between browser and server methods. 2 JSON JSON JavaScript Object Notation Generally preferred by jQuery programmers over XML. Not to mention CSV, plain text, and everything else. Represents data as a JavaScript Object Literal. Essentially just a series of name-value pairs enclosed in curly braces. { Name "CompanyName": "ContactName": "Phone": Value "Exotic Liquids", "Charlotte Cooper", "(171 555-2222)" } Quotes around name are optional if name does not contain space. 3 JSON Values can, themselves, be JavaScript object literals making arbitrarily complex tree structures possible. jQuery provides support for JSON making it easy to use. 4 A JavaScript Object Literal is NOT a String. // A JavaScript object literal var obj = { "Name": "John" }; alert(obj); alert(obj.Name); // A string var str = '{ "Name":"John" }'; alert(str); 5 jQuery.parseJSON() Converts a string into a JavaScript object literal. // A string var str = '{ "name":"John" }'; var obj2 = jQuery.parseJSON(str); alert(obj2.name); parseJSON requires double quotes around names and values in the string to be parsed. as shown above. 6 A jQuery Web Service Client We will rewrite the Server_Calculation example as a web service. Web method Compute_Sum Call the web method from the browser using jQuery Ajax. Use JSON for communciation in both directions. 7 A jQuery Web Service Client Copy the Ajax_jQuery_Demo folder into a new folder. Rename it as jQuery_Web_Service_Client. Open web site in Visual Studio. 9 Add New Item 10 Computation_Service.asmx 11 App_Code/Computation_Service.cs Set Namespace to your own URL. Uncomment the attribute: [System.Web.Script.Services.ScriptService] Replace web method HelloWorld with Compute_Sum, as shown on the next slide. 12 Computation_Service.cs 13 [WebMethod] public string Compute_Sum(string input1, string input2) { Decimal augend = 0.00M; Decimal addend = 0.00M; if (Decimal.TryParse(input1, out augend)) { if (Decimal.TryParse(input2, out addend)) { Decimal sum = augend + addend; return "{ \"result\":\"" + sum.ToString() + "\", " + "\"error_msg\":\"\"}"; } else { return "{ \"result\":\"\", " + "\"error_msg\":\"Second input is not a valid numeric value\" }"; } } else { return "{ \"result\":\"\", " + "\"error_msg\":\"First input is not a valid numeric value\" }"; } } Add New Item: JScript File 15 jQuery_Web_Service_Client.js Bind event handler to button click event. $(document).ready(function () { $('#btnComputeSum').bind('click', Compute_Sum); }); Same as writing onclick="Compute_Sum();" in <asp:button ...> tag. 16 The jQuery ajax Method Use the jQuery ajax method to invoke the remote method $.ajax( ) No parameter for $ ajax parameter will be a JavaScript Object Literal Series of name-value pairs http://api.jquery.com/jQuery.ajax/ 17 jQuery_Web_Service_Client.js function Compute_Sum(evt) { evt.preventDefault(); var input1 = $('#TextBox1').val(); var input2 = $('#TextBox2').val(); // Example: params = "{ 'input1': '4', 'input2': '3' }" var params = "{ " + "'input1': '" + input1 + "', " + "'input2': '" + input2 + "' }"; $.ajax({ type: "POST", dataType: "json", data: params, contentType: "application/json; charset=utf-8", url: "Computation_Service.asmx/Compute_Sum", success: Process_Result, error: Process_Error }); } 18 Processing the Result In the callback function, Process_Result We will get a string representing a JavaScript Object Literal. Use jQuery.parseJSON to convert the string into a JavaScript Object. 19 Callback Functions function Process_Result(response) { var obj = jQuery.parseJSON(response.d); $('#Result').text(obj.result + obj.error_msg); } // This shouldn't happen. function Process_Error(result) { $('#Result').text('ERROR'); } 20 Update Script Name in Ajax_Calculation.aspx 21 Clean Up In Solution Explorer, delete unused files: Ajax_jQuery_Demo.js ajax_responder.aspx Default.aspx ajax_responder.aspx.cs Default.aspx.cs hello.html Server_Calculation.aspx Server_Calculation.aspx.cs 22 Cleaned Up Solution Set Ajax_Calculation.aspx as start page. Build and run. 23 jQuery_Web_Service_Client in Action 24 An Invalid Input End of Section 25 IFABMA Service For a more extensive example, let's create a JavaScript client for the IFABMA Web Service. Have to put the web service on the same server as the web page that will use it. localhost for now. This web service uses XML for communcation with clients. Set up VPN connection. Will need for server communication with scorpius. 26 IFABMA Service Download the IFABMA Web Service website: http://www.cse.usf.edu/~turnerr/Web_Application_Design/Downloads/ 2012_06_28_In_Class/ File IFABMA_Web_Service.zip Extract all files. Drill down to the website folder and open website in Visual Studio. In web.config update connection string with your own username and password Rebuild website. View in Browser 27 We will receive this XML document as the return value of the remote method Get_Members(). Create a JavaScript Client Add New Item Web Form IFABMA_jQuery_Client.aspx Download jQuery http://docs.jquery.com/Downloading_jQuery#Download_jQuery Add to website. Add New Item JScript File jQuery_XML_Web_Service_Client.js 29 IFABMA_jQuery_Client.aspx Just a "Get Data" button, and a <div> for the result. 30 Design View Source on next two slides. 31 IFABMA_jQuery_Client.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="IFABMA_jQuery_Client.aspx.cs" Inherits="IFABMA_Client" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>IFABMA jQuery Client</title> <script language="javascript" type="text/javascript" src="jquery-1.7.2.js" ></script> <script language="javascript" type="text/javascript" src="jQuery_XML_Web_Service_Client.js"></script> </head> 32 IFABMA_jQuery_Client.aspx (continued) <body> <form id="form1" runat="server"> <div> <br /> <br /> <asp:Button ID="btnGetData" runat="server" Text="Get Data" /> <br /> <br /> </div> <div id="Result" ></div> <asp:Label ID="lblMessage" runat="server"></asp:Label> </form> </body> </html> 33 Get Data Operation When user clicks Get Data button In the web method on server Invoke web method Get_Members in IFABMA_Service.cs. Specify callback function. Do database query. Return collection of Members as XML document. When result message is received at browser Completion event fires. Callback function runs For each Member in the XML array Add Member info to the DOM. 34 The jQuery each Method Like "foreach( ){ }" in C# $(selector).each(fn()) Parameter is a function to be applied to each element of jQuery object $(selector). We will use this method to iterate over the Member objects returned by Get_Members. http://api.jquery.com/each/ 35 The jQuery Find Method Finds and returns specified tags within the selection for which it is called. http://api.jquery.com/find/ 36 jQuery_XML_Web_Service_Client.js Bind event handler to button click event. $(document).ready(function () { $('#btnGetData').bind('click', Get_Data); }); Same as writing onclick="Get_Data();" in <asp:button ...> tag. 37 jQuery_XML_Web_Service_Client.js function Get_Data(evt) { evt.preventDefault(); $.ajax({ type: "POST", dataType: "xml", Results returned as XML Method has no parameters data: {}, contentType: "application/text; charset=utf-8", url: "IFABMA_Service.asmx/Get_Members", success: Process_Result, error: Process_Error }); } 38 jQuery_XML_Web_Service_Client.js function Process_Result(xml) { $('#Result').append('<table>'); $(xml).find('Member').each(function () { $('#Result').append('<tr>'); var Company_Name = $(this).find('CompanyName').text(); $('#Result').append('<td>' + Company_Name + '</td>'); Function performed for each Member element in the XML file var Contact_Name = $(this).find('ContactName').text(); $('#Result').append('<td>' + Contact_Name + '</td>'); var Phone = $(this).find('Phone').text(); $('#Result').append('<td>' + Phone + '</td>'); $('#Result').append('</tr>'); }); $('#Result').append('</table>'); } 39 jQuery_XML_Web_Service_Client.js This should never happen. function Process_Error(xml) { $('#Result').text("ERROR"); } Build and run 40 Initial Page 41 Result 42 Add Some Style IFABMA_jQuery_Client.aspx <head> <style type="text/css"> table { border: solid 1px; border-collapse: collapse } td { border: solid 1px; padding: 4px } </style> 43 Result with Style 44 References We have used the following jQuery methods: ajax each http://api.jquery.com/each/ find http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/find/ preventDefault http://api.jquery.com/event.preventDefault/ 45