Benjamin Tinker Team : Web Development Tags : Web Development jQuery

AJAX – Hooking it together.

Benjamin Tinker Team : Web Development Tags : Web Development jQuery

These days nobody likes seeing the page refresh when you submit a form on a website. The preferred visual effect is when clicking a submit button you see a loading icon and then the page magically refreshes itself without ‘blinking’ that  you get from traditional form posts. One of the great features of modern browsers is how JavaScript in the form of jQuery has come back into its own as a front runner developers tool. Using the $.ajax and $.post tools allows for posting all your form information in the back ground and capturing the results.

If you had a simple form say:

<form id="SendMessageForm" method="post">

<label>Messagelabel><input type="text" name="Message" />

<input type="button" value="Send Message" />

form>

<div id="MessageStatus">div>

You could hook this into a jQuery handler that is activated upon clicking the Send Message button. The idea is that you want to have jQuery post all of your information to your handler without having the page itself refresh. This is at the heart of AJAX.

$(document).ready(function () {

$('#SendMessageForm input[type="button"]').click(function (e) {

$.post('/messagehandler.json', $('#SendMessageForm').serialize(), function (data, status) {

if (data.success) {

//handler was successful

$('#MessageStatus').text(data.

MessageResponseSuccess);

}

else {

//handler was unsuccessful

$('#MessageStatus').text(data.

MessageResponseError);

}

});

});

}); 

The code above takes all of the form data and serializes it into JSON and sends it to messagehandler.json. This handler would then perform the operations required and then too return a JSON formatted data. The $.post request can parse data back into most data types be they XML, JSON, Text or HTML. In this instance we are receiving the information as JSON data from messagehandler.json.

In this instance we have the following HTTPHandler set up to take the request. This handler needs to be hooked in at the web.config file via and sections depending on what version of IIS you have installed. 

<httpHandlers>

<add verb="*" path="messagehandler.json " type=" Website.services.MessageHandler, Website.services, Website" />

httpHandlers>

<handlers accessPolicy="Read, Write, Script, Execute">

<add name=”MessageHandler” verb="*" path="messagehandler.json " type=" Website.services.MessageHandler, Website" />

handlers>

namespace Website.services

{

public class MessageHandler : IHttpHandler

{

public bool IsReusable

{

get { return true; }

}

 

public void ProcessRequest(HttpContext context)

{

var jsSerializer = new JavaScriptSerializer();

string output = string.Empty;

 

if (string.IsNullOrEmpty(context.Request["Message"]))

{

jsSerializer.Serialize(new { success = false, Msg = "No message was entered" }).ToString();

}

else

{

//do some more work based on the message//

// ...

// ...

jsSerializer.Serialize(new { success = true, Msg = "Your message was received." }).ToString();

}

 

//write out the response

context.Response.ContentType = "application/json";

context.Response.Write(output);

}

}

}

The handler receives the request and uses the HTTPContext to request the form posted information to check if a message was actually sent. If so we would do the extra work required for processing our message and then build up a JSON response that is serialized back into a format for our original jQuery $.post request. Our jQuery code above is already set up to then receive back the handlers response and checks the success of the post with the (data.success)...  check. It then updates the <div id="MessageStatus">div>  dynamically to show the message sent back by the handler. This is not limited to simple text but can be rich HTML content with its own jQuery event handlers and design elements.

All of this goes together to quickly illustrate the potential for AJAX. You can create very robust forms and user experience for modern websites that gives more and more a application feel to the interaction. You could rework an entire site with clever AJAX and jQuery coding to manipulate your site to extent that the customer never sees a page refresh. They will enjoy a modern application feel of the site and not rely on waiting for the page to post back, a frustration we can all relate to.