Consuming Webservice .net (JSON) using JQuery

In this post i will show how easily you can consume a webservice using JQuery Ajax.

A lot of people have problems with this because sometimes the endpoint is not working or some error appear during the runtime of you web app.

Lets suppouse that you have a webservice named “mywebservice” and i wanna call the method “GetMyFullData(int ID);” that will retrive all the information about someone with a certain ID.

Lets see the code below and how we can do this

$.ajax({
   url: "URL of webservice",
   type: "POST",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: JSON.stringify({   
      ID: 2212,      
   }),
   success: function (response) {
      //if success lets get our json array
      var arrayJson =  $.parseJSON(response.GetMyFullDataResult); //name of the method + "Result"
      //print it
      console.log(arrayJson);
      //loop 
      $.each(arrayJson, function(index, val){
         alert(val.Name); //Do what you want to the Name
      });
   },
   error: function (response) {
      //check the error here
   }

Notes:
To get this working, you need the Json.net dll in your project, you can get it here: Download

now lets see our .net method and how to retreive a list of information

Method

public string GetMyFullData(int ID)
{
   //create a list
   List<Person> lperson = new List<person>();
   
   // Do an SQL or other query to get the person with the ID

   // Append the info to the list if person exists, or like the example, create the person object
   Person p = new Person();
   p.Name = "ricardo";
   p.Age = 23;
   p.Sex = 'm';
   lperson.add(p);

   //return the list   
   return JsonConvert.SerializeObject(lperson);   
}

Class Person

public class Person
{
   public string Name {get; set;}
   public int Age {get; set;}
   public char Sex {get; set;}
}

Response Format
{“name”:”ricardo”,”age”:”23″,”sex”:”m”}

this is a simple and effective way to consuming a webservice .net. So try it and you can leave your questions

4 responses to “Consuming Webservice .net (JSON) using JQuery”

  1. joao lopes says :

    another very good example.
    thanks

Leave a comment