Understand jQuery Ajax Function: Pass JSON Data to Service Method

Welcome to the Understand jQuery Ajax article series. This series explains the Ajax methods of the jQuery library. Our previous articles explained how to consume various types of services using a jQuery Ajax method. You can get them here.

In this article we will learn to send JSON data to Web Method and to return serialized JSON data from the client using a jQuery Ajax method. Since we will use JSON in this article, a basic understanding of JSON and it's format is needed to understand the concept fully. Let's go step-by-step to develop the application.

Step 1: Define Model Class

In this step we will define one model class that we will use to format the data in JSON. Use one .cs class file and use the following code into it.

using System;

using System.Collections.Generic;
using
System.Linq;
using
System.Web; 

namespace WebApplication

{
   
public class person
    {

       
private string name;
       
public string Name
        {

           
get
            {

               
return name;
            }

           
set
            {

                name =
value;
            }

        }
 
       
private string surname;
       
public string Surname
        {

           
get
            {

               
return surname;
            }

           
set
            {

                surname =
value;
            }

        }

    }

}

The class structure is very simple to understand. It contains only two properties called name and surname. So, this is the model class in the application.

Step 2: Create client application to define jQuery Ajax method.

 In this step we will create one .aspx page and we will define the jQuery Ajax function. So, use one .aspx page and use the following code in it.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="WebApplication.JavaScript" %>

<head runat="server">

    <script src="jquery-1.7.1.min.js"></script>
<script>
    
//Jquery.parseJSON function in JQuery
     $(document).ready(
function () { 

         $("#Submit").click(function () {
             var person = {};
             person.Name = $(
"#name").val();


             person.Surname = $(
"#surname").val();
             $.ajax({

                 type:
"POST",
                 url:
"DataService.asmx/SendInformation",
                 contentType:
"application/json; charset=utf-8",
                 data:
"{persons:" + JSON.stringify(person) + "}",
                 success:
function (response) {
                     $(
"#name1").text("Name:- " + response.d.Name);
                     $(
"#surname1").text("Surname:- " + response.d.Surname);
                 },

                 failure:
function (response) {
                     alert(response.d);

                 }

             });

         });
 
     });

</script>
</
head>
<
body>
   
<form id="From1" method="post">
       
<input type="text" name="name" id="name" />
       
<input type="text" name="surname" id="surname" />
       
<input type="button" value="submit" name="Submit" id="Submit" />
   
</form>
   
<div>
       
<div id="name1"></div>
       
<div id="surname1"></div>
   
</div>
</
body>
</
html> 

This is the implementation of the jQuery Ajax function. If we look closely at the button's click event we will find that we are forming one object of the "person" class with form data and then we are passing this form data through the jQuery Ajax function in JSON format. So, our client part is configured. Now we need to create the service that will serve the data to the jQuery Ajax function.

Step 3: Create one Web Service to serve data.

In this step we will create one Web Service to serve the data. Here is sample code for the Web Service.

using System;

using System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Script.Serialization;
using
System.Web.Services; 

namespace WebApplication

{
   
/// <summary>
   
/// Summary description for DataService
   
/// </summary>
    [
WebService(Namespace = "http://tempuri.org/")]
    [
WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.
ToolboxItem(false)]
   
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.
ScriptService]
   
public class DataService : System.Web.Services.WebService
    {

        [
WebMethod]
       
public person SendInformation(person persons)
        {

           
return persons;
        }

    }

} 

When we create the web service we need to ensure to enable the ScriptService attribute over the service class, otherwise the JavaScript client cannot access this web method. Don't forget to put the "[WebMethod]" attribute over the function.

Here within the SendInformation function we are just returning the same object that we are receiving from the Ajax method. In a real scenario we can do many more operations (like data processing) here.

Here is sample output.

JQuery ajax function Output
Conclusion

In this article we saw how to send JSON data to a Web Service using a jQuery Ajax method. Hope you have understood the concept. In a future article we will work more on the jQuery Ajax function.