Adrian Carneiro Adrian Carneiro - 1 year ago 83
Ajax Question

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.

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download