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.

Monday, August 27, 2012

JQuery .autocomplete Basics


So let's say I want to have a text field on a website that prompts users with values that they have previously entered. The solution that I have found myself using over and over is the autocomplete function in Jquery. 

So let's start from basics. In the heading of your page you will need a couple of references:

<script type='text/javascript' src='/jquery/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src="/jQuery/jquery-ui-1.8.18.custom.min.js"></script>

Since this posting there are newer versions of the libraries, but you should be able to get the latest version at the following addresses.

jquery-1.7.1.min.js can be found @ http://jquery.com/download/
jquery-ui-1.8.18.custom.min.js can be found @ http://jqueryui.com/download.

Please feel free to mix and match when pulling a library from http://jqueryui.com/download, it only makes sense to pull what you will need for the site to keep load times small.

So in its simplest and least useful form the autocomplete function can be called like this:

$(function () { $(".SomeClass").autocomplete({source: [“Shop”, “Shopping”, “Writing”]});}); or

$(function () { $("#SomeElement").autocomplete({source: [“Shop”, “Shopping”, “Writing”]});});

Source option must be specified on the autocomplete function.

Use the first scenario when there are multiple textboxes or text areas on a form where you want the list to pop-up.  Use the second when there is a specific textbox or text area where you want to apply the list.  The example above uses a static array and really doesn't do much for us, so lets move on one more step.

With the above code you can define a list of items (in our case Shop, Shopping, and Writing) as an autocomplete list which will appear below a text field as the user types.



So, what do we do when we have a list that is longer than 3 items? What if we have a list that is 30,000 items?  Well, first, you don't put it in an array on the page.  To return a smaller list I would use ajax to call a webservice, or webmethod and the minLength option to set the minimum number of characters the user has to enter before the methods are called.  minLength defines how many letters the user has to enter in a text box before the list will appear.

$(function () { $(".SomeClass").autocomplete(
{
source: [“Shop”, “Shopping”, “Writing”],
minLength: 3
});
});

Now for an intermediate example (ajax): 

In the following example, we call a static method on the page to return our list. 
<script type="text/javascript">

$(function () { $(".SomeClass").autocomplete
({
source:
function (request, response) {
$.ajax
({
url: "Default.aspx/GetCategories", //Page / Static Webmethod
data: "{name:" + JSON.stringify(request.term) + "}", //The parameter name on the method GetCategories is “name” and is of type string.
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response(data["d"]); //Returns an array of strings
},
error: function (xHr, callStatus, errorThrown) {
alert(callStatus);
}
});
},
minLength: 1 //Call this after one letter is typed.
});
});
</script>



Lets break this one down.  We have a source, and minLength as we defined in earlier examples, but instead of an array we are calling a static webmethod on the page called GetCategories. 

[WebMethod]
public static List<string> GetCategories(string name)
{
return new List<string>{“Shop”, “Shopping”, “Writing”};//Do some linq or EF magic here.
}

GetCategories takes a paramater named "name" and returns a list of strings. 



If you copy the code above, there are only a few options that  you will need to change in order to start using the autocomplete function.  I want to start with the error handling.  When I first saw the error function I didn't know what the parameters being passed were.  Here are the definitions or the parameters.

xHr is an XMLHttpRequest
callStatus will contain one of the following values: "timeout", "error", "abort", "parsererror", or null
errorThrown contains an optional exception

A better explaination can be found here.  Just search for the word "error".

Now look at the success option.  The success option returns an array of strings generated by our WebMethod GetCategories.   You can see the formatting of the data in the screen shot below:




The only other two options you will need to change are the url and the data options.
As the name states, the url option defines the url.
url:"Default.aspx/GetCategories", //Page / Static Webmethod

The data option defines the parameters for the method on the url and the value being passed.
data:"{name:"+ JSON.stringify(request.term) + "}", //The parameter name on the method GetCategories is “name” and is of type string.
 
With the data option it is very important to match the name of your parameter exactly.  Hope this helps!  Look for a forthcoming post on using the select option, and some of the fun things we can do with that.