LA.NET [EN]

Aug 19

In this post we’ll keep looking at JQuery’s helper methods for remote calls and we’ll see how we can use the get and post functions for performing HTTP GET and POST requests. Both functions (notice that these are utility functions and not JQuery object methods!) expect several parameters:

$.get( url, [data], [callback], [type] )
$.post( url, [data], [callback], [type] )

The first three parameters are the same as the ones we’ve met in a previous post when we looked at the load method. type is new and lets you indicate the type of response returned from the server. It’s important to set this if you’re getting non HTML/text content from the server side. Currently, it supports the values “xml", "html", "script", "json", "jsonp" and "text".

To show you how easy it is to use this utility function,we’ll start by creating a new handler which expects to retrieve a name from the request and returns an HTML snippet:

public class HowdyHandler : IHttpHandler {
    public void ProcessRequest(HttpContext context) {
        context.Response.ContentType = "text/html";
        context.Response.Write(
                String.Format("Hi <b>{0}</b>!",context.Request["name"]) );
    }
    public bool IsReusable { get { return false; } }
}


Nothing special here, right? Now, take a look at the following HTML snippet:



<body>
    <input type="text" />
    <input type="button" value="Server" />
    <div></div>
</body>
<script type="text/javascript">
    $(function() {
        $("input[type=button]").click(
            function(){
                $.get("HowdyHandler.ashx",
                      { name: $("input[type=text]").val()},
                      function(data){
                        $("div").html(data);
                     });
            });

    });
</script>


We’ve got a textbox and a button which will fire the AJAX request. If you run the previous snippet, you’ll see that you’ll end up doing an HTTP GET request and that you’ll get the “Hi name” message in the div.



Even though getting HTML from the server is handy, it’s not something that I’d do in a typical web app. In my opinion, the server side should only return info  and the HTML formatting should be done by client side code (ie, code running in the browser). In these scenarios, I’ll probably tend to use JSON for the response. Lets update our handler to do that:



public void ProcessRequest(HttpContext context) {
    context.Response.ContentType = "application/json";
    context.Response.Write(
            String.Format("{{ ''name'': ''{0}'' }}", context.Request["name"]) );
}


And now, we need to update our $.get call so that it knows that the response will be in JSON:



<script type="text/javascript">
    $(function() {
        $("input[type=button]").click(
            function(){
                $.get("HowdyHandler.ashx",
                      { name: $("input[type=text]").val()},
                      function(data){
                        $("div").html("Hi <b>" + data.name + "</b>" );
                     },
                     "json");
            });

    });
</script>


With this approach, we build the HTML in the client side. Since we’ve said that the response will be in JSON (notice that last parameter of the $.get function), data will now reference a JS object built from the JSON that is returned from the server.



The $.post utility function is really similar to the $.get function. The main difference is that you end up doing an HTTP POST request instead of a GET. And that’s it for this post. Keep tuned for more on JQuery.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>