Thursday, August 30, 2012

jQuery AJAX


One of the more common items I use with jQuery is AJAX (Asynchronous JavaScript And XML).  Specifically, I tend to use it when I want to give the user some feedback from long lists (.autocomplete) or I want to record the change the user made on the webpage(.sortable).  What is nice is that the calls for each of these are very similar and easy to understand once you have worked with the code once or twice.

For .autocomplete

               source:
                  function (request, response) {
                      $.ajax
                  ({

                      url: " Default.aspx/GetNames",

                      data: "{name:" + JSON.stringify(request.term) + "}",

                      dataType: "json",

                      type: "POST",

                      contentType: "application/json; charset=utf-8",

                      success: function (data) {
                          response(data["d"]);                      },

                      error: function (xhr, callStatus, errorThrown) {
                          alert(callStatus);

                      }

                  });

                  }

For .sortable

                update: function (e, ui) {

                    var item = ui.item;

                    var container = item.parent();

                    var position = (ui.item).index();

                    var section = item.attr("id");

                    var queue = container.attr("listId");

 

                    $.ajax({

 

                        type: "POST",

                        contentType: "application/json",

                        url: "Default.aspx/SaveList",

                        data: "{ ItemData: " + JSON.stringify({ Seq: position + 1, ItemID: section, ListID: queue }) + " }",

                        dataType: "json",

                        error: function (XMLHttpRequest, textStatus, errorThrown) {

                            debugger;

                        },

                        success: function (feedback) {

 

                        }

                    });

                }

The main difference in the code is not in how the method is called but in what is returned.  So let’s break down the basics of what we are passing:

Type:  This will typically contain the value “POST” or “GET”.  I tend to use POST so that the information is contained in the body of the message, and not encoded in the URL by the browser.

contentType:  In the examples above we specify JSON as the data interchange format for the transaction.  This is nice in that it is in a human readable format that makes debugging easier.

url:  Where we will post the data.  Both the examples above post back to a WebMethod.  This is a pretty convenient way to handle the data, but if you choose, you could also post back to a webservice.

Web Method: url: "Default.aspx/SaveList",
Web Service: url: "Default.ashx?obj1=" item1 + "&obj2=" + item2",

data:  This is the data you are passing to the WebMethod.  In the examples above I have used two different techniques for handling the data but both really equate to the same thing.  The first example passes data to an individual parameter on the method.  The second passes a single parameter that corresponds to an object that the method is expecting.

data: "{ ItemData: " + JSON.stringify({ Seq: position + 1, ItemID: section, ListID: queue }) + " }",

This line corresponds to the following class which happens to be the object type the webmethod is expecting.  You may notice that while Seq is an int  but the other two IDs are both strings.  That is because I tend to encrypt all the ids on my forms.

 
public class ItemFromWeb
{
public int Seq {get; set;}
public string ItemID {get; set;}
public string ListID {get; set;}
}

 
[WebMethod]
public static bool SaveList(ItemFromWeb ItemData)
{
return true;
}

 
dataType:  This defines the type of data we are expecting back from the server. 

 
error:  Put in some error handling.

 
success:  Handle any data that was returned by the call.  This will be important in a later post where we will talk about how to handle appending items to the end of text in a textbox using autocomplete.

No comments:

Post a Comment