Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Step by Step working of JSON with all technologies

0.00/5 (No votes)
10 Jun 2015 1  
This article is intended to all those developers who are working on Service Oriented Architecture (SOA) with JavaScript/JQuery. Here I tried to show all the possible ways of handling JSON from client like XMLHttpRequest, JQuery Ajax, Angular js with Web Service, WCF Rest, Asp.NET Web Forms, MVC, MVC

 

Introduction

This article is intended to all those developers who are working on Service Oriented Architecture (SOA) with JavaScript/JQuery. I would like to show you different ways of calling a Service from JavaScript and how JSON message format is transferred across. I will divide this learning into 10 parts. If you want to know about JSON capability with all Microsoft technologies then you are at right spot.

Agenda

  • What is JavaScript Object?
  • Lab 1 – Understand JavaScript object
  • Lab 2 – Array JavaScript objects
  • What is JSON?
  • Lab 3 – Converting JSON string to JavaScript object
  • Lab 4 –Working with Web Service
  • Lab 5 –Working with Asp.NET Web Forms
  • Lab 6- Working with Asp.NET MVC
  • Lab 7-Working with WCF REST services
  • Lab 8-Working Asp.NET Web API
  • What is XMLHttpRequest?
  • Lab 9-Handle JSON with XMLHttpRequest
  • Lab 10-$.getJSON and $.Post
  • Lab 11- Angular JS ($http)
  • Conclusion

What is JavaScript?

mod

JavaScript is a programming language which is mainly developed to work for Web Browsers. It is a client side scripting which executes at client’s web browser rather than web server.

Why JavaScript got importance?

It was not possible for other programming languages like C#, Java, etc. to execute the code on client’s machine browser. So JavaScript language was introduced. This was mainly helpful for adding dynamic & interactive content on HTML pages. But later this JavaScript became so strong that we can then use it to transfer data from client to server and vice versa.

Lab 1: Understand JavaScript Object

Let’s take some time to understand the syntax of representing JavaScript Object.

If I want to represent JavaScript object, I can represent it as shown below:

var employee = { EmployeeName: "Robert", EmployeeCode: "E001" };

In JavaScript, we don’t use new operator, instead we directly declare a variable and assign the value in curly braces. Now to access the EmployeeName, we use dot (.) operator.

alert(employee.EmployeeName);

I am creating a small page where in, on click of button value of employee name will be displayed in a div element.

Steps

1) Open Visual Studio & add a file.

2) Create a button & and a div

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <input type="button" value="JavaScript Object" onclick="DisplayJavascriptObject();" />
 
    <h3>Result:</h3>
    <div id="result"></div>
</body>
</html>

3) Add a JavaScript code to create JavaScript Object and display it in a div, on click of button

<script type="text/javascript">

    function DisplayJavascriptObject() {

        var employee = { EmployeeName: "Robert", EmployeeCode: "E001" };



        document.getElementById("result").innerHTML = employee.EmployeeName;

    }

</script

Output:

 

Lab 2: JavaScript Array.

Now let’s talk about the collection of JavaScript Object. Yes you are right; I am talking about array of JavaScript Object which will consist of employee list. List of Employees will be displayed in a div row by row on click of a button.

Steps:

1) For this I will be creating a new HTML file again.

2) Create a button and add a div again

<input type="button" value="JavaScript Array Object" onclick="DisplayJavascriptArray();" />

    <h3>Result:</h3>
<div id="result"></div>

3) Add the JavaScript code where in an array is created as shown below and using loop each EmployeeName is appended to the div element.

<script type="text/javascript">
        function DisplayJavascriptArray() {
            var arr = [
                        {
                            EmployeeName: "Robert", EmployeeCode: "E001"
                        },
                        {
                            EmployeeName: "Ron", EmployeeCode: "E004"
                        }
            ];
 
            for (i = 0; i < arr.length; i++) {
                document.getElementById("result").innerHTML += arr[i].EmployeeName + "<br/>";
            }
        }
</script

Check the code above, for declaring an array & accessing the array in JavaScript.

Output:

The reason why I talked about JavaScript Object & Array first will come to know soon as you read on.

 

What is JSON?

When we want to communicate between two different technology i.e. - One built in java & other built in .NET, it requires a common language to understand right?

For that we had SOAP (Simple Object Access Protocol). It is an xml notation of data, which is made as standard & can be understandable by any technology.

Actually the format of SOAP looks like as shown below –

But the problem with SOAP format was, it was easily readable by server technologies like Java, .Net, ASP, WPF but it was not that easy to read this SOAP (which is indirectly an XML) from client application like JavaScript.

So we got the concept of JSON? Now why JSON and what is speciality about JSON over SOAP or XML. Let us try to understand it with example

Employee object in XML format -

<Employee>
    <EmployeeName>
    Ron
    </EmployeeName>

If I show same data in JSON format , then it will look like

{
  "Employee": {
    "EmployeeName": "Ron",
    "EmployeeCode": "E004"
  }
}

The Format of JSON is similar to creating an JavaScript Object. This makes these client (JavaScript/ JQuery) more comfortable to understand and parse it.

Note: Today for demos we will use JQuery Ajax to call our services . I will also cover about different other ways of calling server from JavaScript at the end of article i.e - Lab 9 & Lab 10

Lab 3: Converting JavaScript to JSON and vice versa

Converting JSON to JavaScript Object

Step 1 - Create a new HTML file just like above.

Step 2- Define two JSON strings as below.

Simple JSON string:

var jsonemployee= '{"EmployeeName": "Robert", "EmployeCode": "E004"}';

Now take JSON array

var jsonemployees = '[
{"EmployeeName": "Michael", "EmployeeCode": "E004"},
{"EmployeeName": "Robert", "EmployeeCode": "E001}
]';

Step 3-Convert JSON String to JavaScript object using JSON.parse method in JavaScript.

var employee = JSON.parse(jsonemployee);
var employees = JSON.parse(jsonemployees);

Step 4-Write following code to access the elements in the JavaScript Object.

alert(employee.EmployeeName);
alert(employees [0].EmployeeName);

Step 5-Save, Execute and Test the page.

Converting JavaScript Object to JSON

I will be using same above employee & employees object which are already got converted to JavaScript object.

var jsonemployee = JSON.stringify(employee);
var jsonemployees = JSON.stringify(employees);

Now this JSON data can be transmitted over the network to other world which could be in different technology.

Lab 4: Working with Web Service

Step 1- Add a new project & create a Model class Employee

namespace WebServiceXMLEx
{
    public class Employee
    {
        public string EmployeeName { get; set; }
        public string EmployeeCode { get; set; }
    }
}

Step 2-Add a new project & select a Web Service

Step 3- Create 1 web method for returning single Employee based on employee code passed

using System.Web.Script.Services;
 
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
 {
        public static List<Employee> employees = new List<Employee>() { 
            new Employee(){  EmployeeCode = "E004", EmployeeName="Ron"  },
            new Employee(){  EmployeeCode = "E001", EmployeeName="Robert"  }
        };

        
        [WebMethod]
        [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
        public Employee GetEmployee(string code)
        {
           //Database Logic
           return employees.Where(s => s.EmployeeCode == code).SingleOrDefault();
        }    
}

Run the application to check whether Web Service is working properly or not.

Ok it seems to be working fine. Let’s continue.

Explanation

By default WebService can never be called from script i.e. - client like JavaScript or JQuery. To make it happen we explicitly need to say the Web Service to get activated for script. So we need to decorate the Web Service class with attribute.

[System.Web.Script.Services.ScriptService]

To get access to WebMethod on client side, it is must to specify which verb will it use and if needed what is the format of response object. This could be made available using attribute over web method.

[ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet=true)]

Step 4- Add a webpage EmployeeFrom.aspx which will have a text box which will accept Employee code and a button on click of which web service will be called and will return employee details.

Note: As we are going to use JQuery Ajax for calling our webservice, include jQuery library file in our aspx page.

Below is the HTML for Web Page

<div class="maindiv">
          <script src="Scripts/jquery-1.8.2.min.js"></script>
          <input type="text" id="txtEmpCode" class="" />
          <input type="button" value="Search Employee" id="btnEmployee" class="" /> 
          <br />
          <div class="divresult">
              <h5>Search Result: </h5>
              <br />
              <b>Employee Code: </b><span id="empCode"></span>
              <br />
              <b>Employee Name: </b><span id="empName"></span>
          </div>
      </div>

Step 5- Write an Ajax call and pass the value from text box to the webservice in JSON format. On success method, show the response (i.e. - Employee Name & Employee Code) in a span element

Below is the JQuery Ajax call for the webservice to get the data from server.

<script type="text/javascript">
    $(document).ready(function () {

        $('#btnEmployee').click(function () {
            var empCode = $('#txtEmpCode').val();
            $.ajax({
                type: "POST",
                url: "WebService1.asmx/GetEmployee",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify({code:empCode}),
                success: function (result) {
                    if (result != null) {
                        var data = result.d;
                        $('#empCode').text(data.EmployeeCode);
                        $('#empName').text(data.EmployeeName);
                    }
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
        });
    });
</script>

Step 6- Press F5 and execute the application.

Output:

Lab 5: Working with Asp.NET Web Forms

Step 1- Create a Web Application

Note: I am using VS2013, the widget will look different in VS2012. In VS2012, you can select directly Asp.Net Web Forms Application template.

Create an html or web page containing 1 text box for entering the Employee code and a search button

Step 2 - Create an Http Handler. Let’s say ServiceHandler.ashx

Step 3 - Add a new class Employee

public class Employee
    {
        public string EmployeeName { get; set; }
        public string EmployeeCode { get; set; }
    }

Step 4

1) Here I won’t be using any database connection; instead I will use a static collection of Employee details as I did for Lab 4.

public static List<Employee> employees = new List<Employee>() { 
            new Employee(){  EmployeeCode = "E004", EmployeeName="Ron"  },
            new Employee(){  EmployeeCode = "E001", EmployeeName="Robert"  }
        };

2) As you can see my handler is inherited from IHttpHandler interface, so I need to implement the ProcessRequest method which takes context object as a parameter.

To get the data from the request, you can get it using

string empcode = context.Request["code"];

1) Search for employee in the list based on code passed as parameter.

2) Convert the employee object to JSON string using System.Web.Script.Serialization.JavaScriptSerialzier.JavaScriptSerializer class

JavaScriptSerializer serializer = new JavaScriptSerializer();
string JsonEmployeeString = serializer.Serialize(e);

3) Change the content type of response to json specifying the below line

context.Response.ContentType = "text/json";

4) Write the response output back to client

context.Response.Write(JsonEmployeeString);

We are done with service. Now we need to create a client which will consume this handler service.

Step 5- We have already designed the Web Page. Now we need to write the JavaScript to consume the service.

I will be using JQuery Ajax to call the service. Include the JQuery library in your page. If you don’t find it download it from JQuery.com and add the reference of library

Step 6-

1) Add an aspx/html page and add the textbox, a button and span element to show the output

<div class="maindiv">
            <input type="text" id="txtEmpCode" class="" />
            <input type="button" value="Search Employee" id="btnEmployee" class="" /> 
            <br />
            <div id="divresult" class="divresult">
                <h5>Search Result: </h5>
                <br />
                <b>Employee Code: </b><span id="empCode"></span>
                <br />
                <b>Employee Name: </b><span id="empName"></span>
</div>
</div>

2) Add the jquery ajax method which will get called on click of Search Employee button. Add the ajax url with handler which we have created i.e. – ServiceHandler.ashx

$(document).ready(function () {

                $('#btnEmployee').click(function () {
                    var empCode = $('#txtEmpCode').val();
                    $.ajax({
                        type: "GET",
                        url: "ServiceHandler.ashx",
                        contentType: "application/json; charset=utf-8",
                        data: { 'code': empCode },
                        success: function (result) {
                            if (result != null) {
                                var data = result;
                                $('#empCode').text(data.EmployeeCode);
                                $('#empName').text(data.EmployeeName);
                            }
                        },
                        error: function (err) {
                            alert(err.statusText);
                        }
                    });
                });
            });

Step 7-

Now we are done with the changes. Let’s execute it and see the output

Isn’t it simple?

Lab 6: Working with Asp.NET MVC

Step 1-Add a New ‘Asp.Net Web Application’ Project

Note: I am using VS2013, so you may find the template widget bit different from VS2012
In VS2012, you can select ‘Asp.Net MVC 4 Web Application’

Step 2-

1) Add a Controller EmployeeController

2) Add an Action Method named Index and write logic for fetching the employee from employee code passed as a parameter.

public ActionResult Index(string code)
       {
            var emp = employees.Where(e => e.EmployeeCode == code).SingleOrDefault();
            return Json(emp, JsonRequestBehavior.AllowGet);        
}

Explanation:

Note: Same like previous demos, I am not using any database connection instead I am working with static list.

Json() method is MVC inbuilt method which resides in Controller base class. This method serializes the object to JSON string and returns as JsonResult.

Step 3-

1) Now we will create a View (html page) which will contain 1 textbox and a Search button

Same as we have created for previous Demo.

2   One Action Method to call this View

public class HomeController : Controller
   {
        public ActionResult LoadView()
        {
            return View("EmployeeForm");
        }
   }

Output:

3) Write a jQuery Ajax script to call the MVC action method from JavaScript.

$(document).ready(function () {
        $('#btnEmployee').click(function () {
            var empCode = $('#txtEmpCode').val();
            $.ajax({
                type: "GET",
                url: "../Employee/Index",
                contentType: "application/json; charset=utf-8",
                data: { code: empCode },
                success: function (result) {
                    if (result != null) {
                        var data = result;
                        $('#empCode').text(data.EmployeeCode);
                        $('#empName').text(data.EmployeeName);
                    }
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
        });
    });

That’s it rest remains the same.
Good thing about MVC is that any action method either it returns a JsonResult or a View can be easily called using JQuery Ajax.
Pass the value entered from text box as a data to MVC Action Method.
MVC Default Model Binder automatically maps the key passed in JQuery and Action method’s parameter.
No need to use JSON.stringify(), MVC automatically converts JavaScript object to JSON while passing the data.

Step 4- Execute and test it.

Lab 7-Working with WCF REST services

Step 1-

1) Add new Project and select WCF Web Application

2) Create a class Employee and add properties as we did for previous demo.

3) Add New Item => Select WCF Service and provide a good name.

This will add 2 file in the project

4) Create a OperationContract (OperationContract is a method which will be exposed to user when WCF service is hosted)

Open interface IEmployeeService.cs and add the method GetEmployee which will take one parameter ‘code’

[ServiceContract]
public interface IEmployeeService
{
    [OperationContract]
    Employee GetEmployee(string code);
}

5) Now we need to write the implementation for this method. So open EmployeeService.cs class and write implementation for this method as you can see this class already implements IEmployeeService interface

public class EmployeeService : IEmployeeService
    {

        public static List<Employee> employees = new List<Employee>() { 
            new Employee(){  EmployeeCode = "E004", EmployeeName="Ron"  },
            new Employee(){  EmployeeCode = "E001", EmployeeName="Robert"  }
        };

        public Employee GetEmployee(string code)
        {
            var emp = employees.Where(s => s.EmployeeCode == code).SingleOrDefault();
            return emp;
        }
    }

Step 2 - Now we need to make some configuration

1) Go to Web.config file. Navigate to system.serviceModel tag. Inside it ad services tag as shown below.

<system.serviceModel> <services> </services> </system.serviceModel>

2) Now add a service which you want to expose it. So add a service tag inside it and add a attribute name which will point to you service class.

<service name="EmployeeService.EmployeeService"></service>

3) Add a endpoint behaviour within the <system.ServiceModel> tag.

<behaviors>  
<endpointBehaviors>
        <behavior name="restbehaviour">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
</behaviors>

4) Add an endpoint tag within service. This endpoint is an important tag as it specifies ABC of WCF Service where

A - url address of service

B – binding (protocol) we will be using

C - contract class to be exposed.

As we today we are talking about REST service, so we will be using WebHttpBinding

Add the behaviour configuration name which we have create in our previous step

<endpoint address="employee" binding="webHttpBinding" 
    contract="EmployeeService.IEmployeeService" 
    behaviorConfiguration="restbehaviour">
</endpoint>

Step 3

To make service method available, we need to add some more attribute to our OperationContact class.

[WebInvoke(Method="GET",ResponseFormat=WebMessageFormat.Json, UriTemplate="GetEmployeeData/{code}")]
Employee GetEmployee(string code);

Explanation:

WebInvoke attribute which is available in System.ServiceModel.Web namespace takes attribute like

Method-Type of method

ResponseFormat-what should be the format of response

UriTemplate- to specify the user friendly url. As we want to pass code as a parameter and it’s a GET request, the uri template takes the code within curly braces which means it’s a dynamic value which is passed when service is called.

If we don’t add that code within curly braces we will get an error shown below

Step 4- Execute and check whether service is active and giving expected result or not.

Step 5 - Create a client for consuming the REST service. We will be using JQuery Ajax for consuming the service.

1) Add a simple html page. Create 1 textbox and 1 button as did in previous demo.

2) Add a JQuery library reference.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

3) Add a JQuery Ajax method on button click which will accept employee code and retrieve employee details by calling REST service.

<script type="text/javascript">
        $(document).ready(function () {
             $('#btnEmployee').click(function () {
                var empCode = $('#txtEmpCode').val();
                $.ajax({
                    type: "GET",
                    url: "http://localhost:14109/EmployeeService.svc/restservice/GetJsonTestData/" + empCode,
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        if (result != null) {
                            var data = result.GetEmployeeResult;
                            $('#empCode').text(data.EmployeeCode);
                            $('#empName').text(data.EmployeeName);
                        }
                    },
                    error: function (err) {
                        alert(err.statusText);
                    }
                });
            });
        });
</script>

4) Keep the service running and execute the page and test it

Lab 8-Working Asp.NET Web API

Step 1-

1) Add a New Project and select ASP.NET Web Application

Select Web API.

Note: I am using VS2013, you will find bit different wizard when working with VS2012. In VS2012, you need to select Asp.NET MVC 4 Web Application.

2) Add a controller by right clicking on Controller folder. You will get this screen. Select empty Web API 2 Controller. Then give a name to Web API and click Ok.

You will find that the controller is almost similar to MVC controller, but this controller extends from ApiController class.

Step 2-

Create a Model Employee with 2 properties as we did for all previous demos.

public class Employee
    {
        public string EmployeeCode { get; set; }
        public string EmployeeName { get; set; }
}

Step 3-

1) Add an API method which you want to expose to client. Let me give a name as GetEmployee

public Employee GetEmployee(string code)
        {
            Employee emp = employees.Where(s => s.EmployeeCode == code).SingleOrDefault();
            return emp;
       }

2) Execute and check whether API is running properly or not.

You may be worrying how it is calling the service when I passed this url?

Keep some point in mind-

-Web API routing is configured by below route register in global.asax.

-By default, if we don’t pass the method type like GET /POST web API works on the prefix of your API method name. If it starts with GET, API will be considered as GET method and if it starts with POST then method will be considered as POST.

- You have different method name (not prefixed with GET) and need to work for GET request type only, then decorate the method with HttpGet / HttpPost / HttpPut/ HttpDelete attribute

Eg-
[HttpGet]
public string FindEmployee() { /*code */}

Step 4-

1) Create a View / Html UI consisting of 1 textbox and 1 button same as we did for other demos.

An Action Method to call this view.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

2) Add a jQuery library reference

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

3) We will use JQuery Ajax to call our Web API

<script type="text/javascript">
        $(document).ready(function () {
            $('#btnEmployee').click(function () {
                var empCode = $('#txtEmpCode').val();
                $.ajax({
                    type: "GET",
                    url: "../api/Employee",
                    data: {code: empCode},
                    success: function (result) {
                        if (result != null) {
                            $('#empCode').text(result.EmployeeCode);
                            $('#empName').text(result.EmployeeName);
                        }
                    },
                    error: function (err) {
                        alert(err.statusText);
                    }
                });
            });
        });
    </script>

If you have observed, we haven’t used JSON.stringify() while passing the parameter. WEBAPI can automatically convert JavaScript object to JSON object.

Some point to keep in mind-

-By default WebAPI emits JSON format. If you want API to emit data in xml format, specify datatype: ‘xml’ in our Ajax call as shown below

4) Execute and test it

What is XMLHttpRequest?

In my entire example I have used $.ajax method of JQuery. This method was first introduced as a technique to send request to service using client script using JQuery.

To make you aware before this method came into existence, we had something called an XMLHttpRequest object which was used to exchange data between client and server using traditional JavaScript.

You know what $.ajax() which you use it today, is just a wrapper to this traditional method.

I would like to show the technique of using XMLHttpRequest, later you can modify all of the technologies which we learned above to work with this.

Lab 9: Handle JSON with XMLHttpRequest

XMLHttpRequest GET request

Step 1-

1) Create an html page in our same WebAPI application which we have practiced in our previous lab. Let’s says AjaxXMLHttpRequest.html.

2) Take a textbox to enter employee code and a button

<input id="txtempcode" type="text" />
      <input type="button" value="XMLHttpRequest GET" id="btn1" class="btn" />

Step 2-

Write a JavaScript for calling the Web API get request. Call this button on button click.

   <script type="text/javascript">
        function CallGETXmlHttpRequest() {
            var empcode = document.getElementById('txtempcode').value;
            var xmlhttp = new XMLHttpRequest();
            var data = "code=" + empcode;
            var url = "../api/Employee";

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var myArr = JSON.parse(xmlhttp.responseText);
                    myFunction(myArr);
                }
            }
            xmlhttp.open("GET", url + '?' + data, true);
            xmlhttp.send();
        }
function myFunction(arr) {
            document.getElementById('empCode').innerHTML = arr.EmployeeCode;
            document.getElementById('empName').innerHTML = arr.EmployeeName;
        }
</script>

Explanation:

  • Create an XMLHttpRequest object.
  • Open the connection by passing
    • the type of Request (GET/POST)
    • service url. As it’s a GET request you can pass the parameter in query string.
    • Flag indicating asynchronous call.
  • Call the Send method
  • Handle onreadystatechange event of XMLHttpRequest object. Within this event check if readyState is equal to 4 and status is equal to 200. This event identifies for successful call to service and a response from server.

That’s it.

Step 3-

Execute and test it

XMLHttpRequest POST request

Step 1- Take another button on same page

<input type="button" value="XMLHttpRequest POST" id="btn2" class="btn" />

Step 2- Write a JavaScript method

function CallPOSTXmlHttpRequest() {
            var empcode = document.getElementById('txtempcode').value;
            var xmlhttp = new XMLHttpRequest();
            var url = "../api/Employee";
            var data = { EmployeeName: "Pradeep", EmployeeCode: empcode };
           
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var myArr = JSON.parse(xmlhttp.responseText);
                    myFunction(myArr);
                }
            }
            xmlhttp.open("POST", url, true);
            xmlhttp.setRequestHeader('Content-Type', 'application/json');
            xmlhttp.send(JSON.stringify(data));
        }

        function myFunction(arr) {
            document.getElementById('empCode').innerHTML = arr.EmployeeCode;
            document.getElementById('empName').innerHTML = arr.EmployeeName;
        }

Explanation-

For POST request the only change is when you want to pass any parameter in JSON format then you need use JSON.stringify as we did in previous example and pass that parameters as an argument to xmlhttp.send() method.
Also set the request header to get response in json format.

xmlhttp.setRequestHeader('Content-Type','application/json');

Lab 10: $.getJSON and $.Post

$.getJSON()

This is an advanced version of jQuery ajax which specially meant for handling GET request only that too of response type JSON.

Step 1- Create an html page AjaxGETPOST.html similar as we did for XMLHttpRequest and the controls

<input id="txtempcode" type="text" />
<input type="button" value="$.GetJson" id="btn3" class="btn" />

Step 2- Add a JQuery library. $.getJSON only works if jquery library is include in the file.

<script src="Scripts/jquery-1.10.2.min.js"></script>

Step 3- Add a JQuery script function and call on button click.

function CallGetJson() {
            var empcode = $('#txtempcode').val();
            $.getJSON("../api/Employee", { code: empcode }).done(function (result) {
                if (result != null) {
                    $('#empCode').text(result.EmployeeCode);
                    $('#empName').text(result.EmployeeName);
                }

            }).fail(function (err) {
                alert(err.statusText);
            });
        }

Explanation:

  • $.getJSON takes first parameter as url.
  • The second parameter is data to be passed which will internally pass as a querystring.
  • done event to handle successful response
  • fail event to handle error

$.post()

Step 1 – Add another button

<input type="button" value="$.Post" id="btn4" class="btn" />

Step 2- Add a JQuery library. $.getJSON & $.post only works if jquery library is include in the file.

<script src="Scripts/jquery-1.10.2.min.js"></script>

Step 3- Add a javascript code and call on button click

function CallPostJson() {
            var empcode = $('#txtempcode').val();
            $.post("../api/Employee", { EmployeeCode: empcode, EmployeeName: "Pradeep" }).done(function (result) {
                if (result != null) {
                    $('#empCode').text(result.EmployeeCode);
                    $('#empName').text(result.EmployeeName);
                }

            }).fail(function (err) {
                alert(err.statusText);
            });
        }

Output-

Lab 11: Angular JS ($http)

$http is a core angular service which is mainly used to have a communication between the remote http server via XMLHttpRequest

The $http service is a single function which takes a single argument that is used to generate an HTTP request and in return gives you a promise with two $http specific methods: success and error.

For GET request it will be $http.get() and for POST request it will be $http.post()

$http.get()

Step 1-

1) Create an html page in our same WebAPI application which we have practiced in our previous lab. Let’s says AngularGETPOST.html.

2) Take a textbox to enter employee code and a button

3) Add a reference of angular js library

<script src="Scripts/angular.js"></script>

Here we will try to use some nice capability of angular i.e. - databinding 

<div class="maindiv" ng-app="myapp" ng-controller="employeeController">

        <input id="txtempcode" type="text" ng-model="myData.searchtext" />
        <input type="button" value="$http Get" id="btn3" class="btn" ng-click="myData.doGetClick()" />
        <div id="divresult" class="divresult">

            <h5>Search Result: </h5>

            <b>Employee Code: </b><span id="empCode">{{employee.EmployeeCode}}</span>

            <br />
            <b>Employee Name: </b><span id="empName">{{employee.EmployeeName}}</span>

        </div>
</div>

Explanation: 

If you see the html code, you will find some ng attribute all over. These are actually the angular syntax

  • ng-app = This is an angular directive to activate the angular by instantating.
  • ng-controller= This directive actually specifies the area that needs to be controlled by the controller. Here div is the area to be controlled by controller employeecontroller.
  • ng-model= It’s a model bound to the html element
  • ng-click = Angular events
  • {{  }}= Binding expression 

Step 2- Write an angular code for calling web API

angular.module("myapp", [])

      .controller("employeeController", function ($scope, $http) {

          $scope.myData = {};
          $scope.employee = {};

          $scope.myData.doGetClick = function (item, event) {
              var url = "../api/Employee";
            
              var params = {
                  code: $scope.myData.searchtext
              };


              $http.get(url, { params: params })
                  .success(function (result) {
                      $scope.employee = result;
                  })
              .error(function (err) {
                  alert(err.statusText);
             });
          }
}

Explanation

  • This line is used to activate the angular first and then pass the controller name to activate it.

  • $scope is the this (current) object for the controller. Anything attached to $scope will be called as model ans $http is the service of angular we will be using.

    angular.module("myapp", [])
    .controller("employeeController", function ($scope, $http) {
  • Model to be used.
    $scope.myData = {}
    $scope.employee = {};

Step 3- Click on button and test it. You will see the output is placed in the expression automatically on click though I have not written any set statement for <span/> in success method. I have only set the $scope.employee object. This is the power of angular

 


  • $scope.myData.doGetClick & $scope.myData.searchText are the model’s method and property which we bound to the button and textbox. 

  • $http.get() method takes Web API url as the first and data as the second parameter where I am passing JSON data as a input. On success function we will get the output of Web API

$http.post()

This is also almost similar to what we have seen in $http.get . Let start.

Step 1- Take another button on the screen 

<input type="button" value="$http Post" id="btn4" class="btn" ng-click="myData.doPostClick()" />

Write the script for doPostClick function.

$scope.myData.doPostClick = function (item, event) {
              var url = "../api/Employee";

              var Employee = {
                  EmployeeCode: 'E005',
                  EmployeeName: 'Pradeep'
              };

              $http.post(url, Employee)
                  .success(function (result) {
                      $scope.employee = result;
                  })
                 .error(function (err) {
                  alert(err.statusText);
              });
          }

$http.post accepts 2 parameter first is the url of Web API and second is the data to be posted. Here I am passing employee object. Rest all remains the same.

Step 2- Execute and test it

Conclusion

Here we comple all our Labs of working with JSON and observing it capability . This is how; it is very simple to work with JSON format when client comes to JavaScript.  I hope you liked this article. Please does comment on this article if you find it good or bad, your comment will definitely help me to serve you better.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here