Wednesday, June 25, 2014

Step by step how to send an Ajax request to get a Json response

        By Carmel Schvartzman


In this tutorial we'll learn how to send an Ajax request to get a Json response in ASP.NET MVC 4. We'll use the $.ajax() method to render just a sample JSON object traveling round-trip from client side to server side , and back from server side to client side.

We'll want to render a JSON object , via an Ajax request, as follows:





The HTML markup will be just a text input, a <span> to get the response text, and a button to send the request :



At the javascript file, we MUST specify that the response we are expecting is in JSON format, using the parameter "dataType" :

And the Controller will return a JsonResult containing a simple string but in JSON format:



The response will be showed in the web page as follows :





Now we want to get a JSON OBJECT from the server. Let's include the message inside an anonymous object and serialize it as JSON using the Json() constructor : 


The jQuery code will expects JSON of course (by using the "dataType" parameter) but this time we need to consider that the returned "data" IS AN OBJECT : therefore we get the message using object notation to get the object's property :  data . MsgFromServer : 




This is the jQuery code to copy-paste :
 $("input[id!=hello]").dblclick(function () {
        var input =  "{'msg':'" +  $("[id*=message]").val() + "'}";
        $.ajax({
            url: "Blog/SayHello",
            data: input ,
            contentType: "application/json",
            dataType: "json",
            type: "POST",
            success: function (data) {
                $("[id|=result]").prepend($("<b></b>").html("<i>" + data.MsgFromServer + "</i>"));
            }
        })
    });
 

Also, here you have the markup :

<h2>Get JSON from Server Side via Ajax</h2>
<input type="text" id="message" />
<input type="button" id="btn-getdatafrom-server" value="Get data from server" />
<span id="result"></span>

Then we send the request as follows:


And the response this time is a JSON object (with the message as a property):




This is the rendered JSON object in the web page :







In this tutorial we've learned how to send an Ajax request to get a Json response in ASP.NET MVC 4.  
That's all!! 
Happy programming.....

כתב: כרמל שוורצמן