To use a web service using jQuery, i.e. to call a WCF service, you either use jQuery.ajax () or jQuery.getJSON (). In this article, I used the jQuery.ajax () method.
To specify a query, first define a variable. This will be useful if you call several methods and create another js file to call the WCF service.
<script type="text/javascript"> var Type; var Url; var Data; var ContentType; var DataType; var ProcessData;
The following function initializes the variables defined above to call the service.
function WCFJSON() { var userid = "1"; Type = "POST"; Url = "Service.svc/GetUser"; Data = '{"Id": "' + userid + '"}'; ContentType = "application/json; charset=utf-8"; DataType = "json"; varProcessData = true; CallService(); }
The CallService function sends requests to the service, setting the data to $ .ajax.
// Function to call WCF Service function CallService() { $.ajax({ type: Type, //GET or POST or PUT or DELETE verb url: Url, // Location of the service data: Data, //Data sent to server contentType: ContentType, // content type sent to server dataType: DataType, //Expected data format from server processdata: ProcessData, //True or False success: function(msg) {//On Successfull service call ServiceSucceeded(msg); }, error: ServiceFailed// When Service call fails }); } function ServiceFailed(result) { alert('Service call failed: ' + result.status + '' + result.statusText); Type = null; varUrl = null; Data = null; ContentType = null; DataType = null; ProcessData = null; }
Note. The following code checks the result.GetUserResult statement, so your result object gets the property of your service method name + Result. Otherwise, it will give an error, like an object not found in Javascript.
function ServiceSucceeded(result) { if (DataType == "json") { resultObject = result.GetUserResult; for (i = 0; i < resultObject.length; i++) { alert(resultObject[i]); } } } function ServiceFailed(xhr) { alert(xhr.responseText); if (xhr.responseText) { var err = xhr.responseText; if (err) error(err); else error({ Message: "Unknown server error." }) } return; } $(document).ready( function() { WCFJSON(); } ); </script>