Friday, September 20, 2013

How to call webservice from JQuery

Hey guys,

Today we are going to show you how easy it is to call web service methods and parse the results.

Things you need to know:

  • JQuery
  • WebServices
  • JSON
But let's assume you know a little bit about everything mentioned above.
First thing you need to create your web service with some methods you are going to call in future. To make it work with JQeury it would be better to return results in JSON format (but this is in case you want to return data tables and other objects, if it is only a string, don't worry at all)
So let's assume you have a webservice at "Services/YourService.asmx" and it has one method 'GetUserData(string userId)'
How are we going to call it from JQuery, pass a parameter and receive something back?

            $.ajax({
                type: "POST",
                url: "/Services/YourService.asmx/GetUserData",
                data: "{'userId':'" + userId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    var c = jQuery.parseJSON(msg.d);
                    window.alert(c[0]["FirstName"] + " " + c[0]["LastName"] + ", UserName: " + c[0]["UserName"]);
                },
                failure: function (error) {
                    window.alert('There was a problem connecting to the server. Please try again.');
                }
            });

As simple as that :-) So we call the method, receive json string back, parse it and display the results.

Too easy right? Well this is what we told you:-)


Cheers,
Your GPTeam

0 comments:

Post a Comment