consume a .net webservice using jQuery
- by Babunareshnarra
Implementation shows the way to consume web service using jQuery. The client side AJAX with HTTP POST request is significant when it comes to loading speed and responsiveness.Following is the service created that return's string in JSON.[WebMethod][ScriptMethod(ResponseFormat = ResponseFormat.Json)]public string getData(string marks){ DataTable dt = retrieveDataTable("table", @" SELECT * FROM TABLE WHERE MARKS='"+ marks.ToString() +"' "); List<object> RowList = new List<object>(); foreach (DataRow dr in dt.Rows) { Dictionary<object, object> ColList = new Dictionary<object, object>(); foreach (DataColumn dc in dt.Columns) { ColList.Add(dc.ColumnName, (string.Empty == dr[dc].ToString()) ? null : dr[dc]); } RowList.Add(ColList); } JavaScriptSerializer js = new JavaScriptSerializer(); string JSON = js.Serialize(RowList); return JSON;}Consuming the webservice $.ajax({ type: "POST", data: '{ "marks": "' + val + '"}', // This is required if we are using parameters contentType: "application/json", dataType: "json", url: "/dataservice.asmx/getData", success: function(response) { RES = JSON.parse(response.d); var obj = JSON.stringify(RES); } error: function (msg) { alert('failure'); }});Remember to reference jQuery library on the page.