Basic Simple + jQuery + JSON example

I’m trying to learn how to make a simple call to the server from Javascript/jQuery. I’ve been trying to learn and could not find a tutorial with those simple steps.

I want to send a message to the server with two parameters (a DateTime and a String) and get back a DateTime. I want to do that via JSON.

  • How would the code in the server look like (structure only)?
  • Is there something special I should do on the server side? And how about security?
  • How would I implement the call in jQuery?
  • And how would I handle the result?

I’m most interested on code structure.


I found the answer below great to get me started. However, I recently stumbled upon Full ASP.NET, LINQ, jQuery, JSON, Ajax Tutorial. It’s just a fantastic and very didactic step-by-step that I want to share with anyone else who comes across this question in the future.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There are several ways that you can do this; this will serve as a single example.

You could write something like this for your jQuery code:

urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
                url: urlToHandler,
                data: jsonData,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json',
                success: function(data) {                        
                error: function(data, status, jqXHR) {                        
                    alert('There was an error.');
            }); // end $.ajax

Next, you need to create a “generic handler” in your project. In your generic handler, use Request.Form to read the values passed in as json. The code for your generic handler could look something like this:

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
    public void ProcessRequest(HttpContext context)
        context.Response.ContentType = "application/json";

        DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
        string stringParam = (string)Request.Form["stringParam"];

        // Your logic here

        string json = "{ "responseDateTime": "hello hello there!" }";

See how this work out. It will get you started!

Update: I posted this code at the CodeReview StackExchange:

Method 2

If you are using jQuery you could do it with a GET or POST.

$.get ('<url to the service>',
       { dateParam: date, stringParam: 'teststring' },
       function(data) {
          // your JSON is in data

$.post ('<url to the service>',
       { dateParam: date, stringParam: 'teststring' },
       function(data) {
          // your JSON is in data

Note that the name of the parameters in (e.g. dateParam, stringParam) need to be the same as the name of the parameters your service method is expecting. Also that your service will need to format the result as JSON, the data parameter in the call back will contain anything your service sends back (e.g. text, xml, json, etc).

See the jQuery documentation for $.ajax, $.get, $.post:,,

Method 3

Here sample code using jquery ajax call and on serverside webmethod returns jSon format data.
Jquery :

    var aData= [];
     aData[0] = “2010”; 
     var jsonData = JSON.stringify({ aData:aData});
                type: "POST",
                url: "Ajax_function/myfunction.asmx/getListOfCars",  //getListOfCars is my webmethod 
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: "json", // dataType is json format
                success: OnSuccess,
                error: OnErrorCall
function OnSuccess(response.d)) {
function OnErrorCall(response)) { console.log(error); }

Codebehind : Here a webmethod which is returning json format data i.e list of cars

public List<Cars> getListOfCars(list<string> aData) 
    SqlDataReader dr;
    List<Cars> carList = new List<Cars>();
         using (SqlConnection con = new SqlConnection(cn.ConnectionString))
            using (SqlCommand cmd = new SqlCommand())
               cmd.CommandText = "spGetCars";
               cmd.CommandType = CommandType.StoredProcedure;
               cmd.Connection = con;
               cmd.Parameters.AddWithValue("@makeYear", aData[0]);
               dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
               if (dr.HasRows)
                  while (dr.Read())
                       string carname=dr[“carName”].toString();
           string carrating=dr[“carRating”].toString();
            string makingyear=dr[“carYear”].toString();
           carList .Add(new Cars{carName=carname,carRating=carrating,carYear=makingyear}); 
        return carList 

//Created a class

Public class Cars {
public string carName;
public string carRating;
public string carYear;

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x