5 Ways to Make Ajax Calls with jQuery

Such a great post I had to back it up for reference sake, in case it ever goes down.

Source: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

By: Piao Yishi

Source File:

Live Demo: http://nettuts.s3.amazonaws.com/412_ajaxCalls/DEMO/index.htm

What is AJAX
This section is for those who have no idea what AJAX is. If you don't fall into this category, feel free to skip to the next section.

AJAX stands for asynchronous JavaScript and XML. If you see another term XHR, which is shorthand for XML HTTP request, it's the same thing. Don't be afraid of this jargon; AJAX is not rocket science.

  • In Gmail, switch from inbox to draft. Part of the page is changed, but the page is not refreshed. You remain on the same page. Url has not changed (except for the #draft at the end of the url, but that's still the same webpage).
  • In Google Reader, select a feed. The content changes, but you are not redirected to another url.
  • In Google Maps, zoom in or zoom out. The map has changed, but you remain on the same page.

The key to AJAX's concept is "asynchronous". This means something happens to the page after it's loaded. Traditionally, when a page is loaded, the content remains the same until the user leaves the page. With AJAX, JavaScript grabs new content from the server and makes changes to the current page. This all happena within the lifetime of the page, no refresh or redirection is needed.

Caching AJAX

Now we should know what AJAX actually is. And we know that, when Gmail refreshes some content without redirection, an AJAX call is made behind the scenes. The requested content can either be static (remains exactly the same all the time, such as a contact form or a picture) or dynamic (requests to the same url get different responses, such as Gmail's inbox where new mails may show up any time).

For static content, we may want the response cached. But for dynamic content, which can change in a second's time, caching AJAX becomes a bug, right? It should be noted that Internet Explorer always caches AJAX calls, while other browsers behave differently. So we'd better tell the browser explicitly whether or not AJAX should be cached. With jQuery, we can accomplish this simply by typing:

view plaincopy to clipboardprint?

  1. $.ajaxSetup ({ 
  2.     cache: false
  3. }); 
	$.ajaxSetup ({
		cache: false
1. load(): Load HTML From a Remote URL and Inject it into the DOM

The most common use of AJAX is for loading HTML from a remote location and injecting it into the DOM. With jQuery's load() function, this task is a piece of cake. Review this demo and we'll go over some uses one by one.

Minimal Configuration

Click on the first button named "load()." A piece of HTML is injected into the page, exactly what we were talking about. Let's see what's going on behind the scenes.

Below is the JavaScript code for this effect:

view plaincopy to clipboardprint?

  1.     $.ajaxSetup ({ 
  2.         cache: false
  3.     }); 
  4. var ajax_load = "<img src='img/load.gif' alt='loading...' />"; 
  5. //  load() functions
  6. var loadUrl = "ajax/load.php"; 
  7.     $("#load_basic").click(function(){ 
  8.         $("#result").html(ajax_load).load(loadUrl); 
  9.     }); 
	$.ajaxSetup ({
		cache: false
	var ajax_load = "<img src='img/load.gif' alt='loading...' />";
//	load() functions
	var loadUrl = "ajax/load.php";
  1. $.ajaxSetup forces the browser NOT to cache AJAX calls.
  2. After the button is clicked, it takes a little while before the new HTML is loaded. During the loading time, it's best to show an animation to provide the user with some feedback to ensure that the page is currently loading. The "ajax_load" variable contains the HTML of the loading sign.
  3. "ajax/load.php" is the url from which the HTML is grabbed.
  4. When the button is clicked, it makes an AJAX call to the url, receives the response HTML, and injects it into the DOM. The syntax is simply $("#DOM").load(url). Can't be more straightforward, hah?

Now, let's explore more details of the request with Firebug:

  1. Open Firebug.
  2. Switch to the "Net" tab. Enable it if it's disabled. This is where all HTTP request in the browser window are displayed.
  3. Switch to "XHR" tab below "Net". Remember the term "XHR?" It's the request generated from an AJAX call. All requests are displayed here.
  4. Click on the "load()" button and you should see the following.

The request is displayed, right? Click on the little plus sign to the left of the request, more information is displayed.

Click on the "Params" tab. Here's all parameters passed through the GET method. See the long number string passed under a "_" key? This is how jQuery makes sure the request is not cached. Every request has a different "_" parameter, so browsers consider each of them to be unique.

Click on the "Response" tab. Here's the HTML response returned from the remote url.

Load Part of the Remote File

Click on "load() #DOM" button. We notice that only the Envato link is loaded this time. This is done with the following code:

view plaincopy to clipboardprint?

  1. $("#load_dom").click(function(){ 
  2.     $("#result") 
  3.         .html(ajax_load) 
  4.         .load(loadUrl + " #picture"); 
  5. }); 
			.load(loadUrl + " #picture");

With load(url + "#DOM"), only the contents within #DOM are injected into current page.

Pass Parameters Through the GET Method

Click on the "load() GET" button and open firebug.

view plaincopy to clipboardprint?

  1. $("#load_get").click(function(){ 
  2.     $("#result") 
  3.         .html(ajax_load) 
  4.         .load(loadUrl, "language=php&version=5"); 
  5. }); 
			.load(loadUrl, "language=php&version=5");

By passing a string as the second param of load(), these parameters are passed to the remote url in the GET method. In Firebug, these params are shown as follows:

Pass Parameters Through the POST Method

Click on the "load() POST" button and open Firebug.

view plaincopy to clipboardprint?

  1. $("#load_post").click(function(){ 
  2.     $("#result") 
  3.         .html(ajax_load) 
  4.         .load(loadUrl, {language: "php", version: 5}); 
  5. }); 
			.load(loadUrl, {language: "php", version: 5});

If parameters are passed as an object (rather than string), they are passed to the remote url in the POST method.

Do Something on AJAX Success

Click on "load() callback" button.

view plaincopy to clipboardprint?

  1. $("#load_callback").click(function(){ 
  2.     $("#result") 
  3.         .html(ajax_load) 
  4.         .load(loadUrl, null, function(responseText){ 
  5.             alert("Response:\n" + responseText); 
  6.         }); 
  7. }); 
			.load(loadUrl, null, function(responseText){
				alert("Response:\n" + responseText);

A function can be passed to load() as a callback. This function will be executed as soon as the AJAX request is completed successfully.

2. $.getJSON(): Retrieve JSON from a Remote Location

Now we'll review the second AJAX method in jQuery.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It's very convenient when exchanging data programmatically with JSON.

Let's review an example.

Find the $.getJSON() section in the demo page, type in some words in your native language, and click detect language.

view plaincopy to clipboardprint?

  1. //  $.getJSON()
  2. var jsonUrl = "ajax/json.php"; 
  3.     $("#getJSONForm").submit(function(){ 
  4. var q = $("#q").val(); 
  5. if (q.length == 0) { 
  6.             $("#q").focus(); 
  7.         } else { 
  8.             $("#result").html(ajax_load); 
  9.             $.getJSON( 
  10.                 jsonUrl, 
  11.                 {q: q}, 
  12. function(json) { 
  13. var result = "Language code is \"<strong>" + json.responseData.language + "\""; 
  14.                     $("#result").html(result); 
  15.                 } 
  16.             ); 
  17.         } 
  18. return false; 
  19.     }); 
//	$.getJSON()
	var jsonUrl = "ajax/json.php";
		var q = $("#q").val();
		if (q.length == 0) {
		} else {
				{q: q},
				function(json) {
					var result = "Language code is \"<strong>" + json.responseData.language + "\"";
		return false;

Let's jump to Line 9:

  1. $.getJSON doesn't load information directly to the DOM. So the function is $.getJSON, NOT $("#result").getJSON. (There are pairs of similar looking functions in jQuery such as $.each() and each(). Check out their respective documentation for more information.)
  2. $.getJSON accepts three parameters. A url, parameters passed to the url and a callback function.
  3. $.getJSON passes parameters in GET method. POSTing is not possible with $.getJSON.
  4. $.getJSON treats response as JSON.
$.getJSON's function name is NOT camel-cased. All four letters of "JSON" are in uppercase.

Look at the response in JSON format in Firebug. It's returned from Google Translate API. Check out ajax/json.php in source files to see how language detection works.

3. $.getScript(): Load JavaScript from a Remote Location

We can load JavaScript files with $.getScript method. Click on "Load a Remote Script" button in the demo page; let's review the code for this action.

view plaincopy to clipboardprint?

  1. //  $.getScript()
  2. var scriptUrl = "ajax/script.php"; 
  3.     $("#getScript").click(function(){ 
  4.         $("#result").html(ajax_load); 
  5.         $.getScript(scriptUrl, function(){ 
  6.             $("#result").html(""); 
  7.         }); 
  8.     }); 
//	$.getScript()
	var scriptUrl = "ajax/script.php";
		$.getScript(scriptUrl, function(){
  1. $.getScript accepts only two parameters, a url, and a callback function.
  2. Neither the GET nor POST params can be passed to $.getScript. (Of course you can append GET params to the url.)
  3. JavaScript files don't have to contain the ".js" extension. In this case, the remote url points to a PHP file. Let your imagination fly and you can dynamically generate JavaScript files with PHP.

See the response JavaScript in Firebug.

4. $.get(): Make GET Requests

$.get() is a more general-purpose way to make GET requests. It handles the response of many formats including xml, html, text, script, json, and jonsp. Click on the "$.get()" button in the demo page and see the code.

view plaincopy to clipboardprint?

  1. //  $.get()
  2.     $("#get").click(function(){ 
  3.         $("#result").html(ajax_load); 
  4.         $.get( 
  5.             loadUrl, 
  6.             {language: "php", version: 5}, 
  7. function(responseText){ 
  8.                 $("#result").html(responseText); 
  9.             }, 
  10. "html"
  11.         ); 
  12.     }); 
//	$.get()
			{language: "php", version: 5},
  1. $.get() is completely different, as compared to get(). The latter has nothing to do with AJAX at all.
  2. $.get accepts the response type as the last parameter, which makes it more powerful than the first functions we introduced today. Specify response type if it's not html/text. Possible values are xml, html, text, script, json and jonsp.

5. $.post(): Make POST Requests

$.post() is a more general-purpose way to make POST requests. It does exactly the same job as $.get(), except for the fact that it makes a POST request instead.

view plaincopy to clipboardprint?

  1. //  $.post()
  2.     $("#post").click(function(){ 
  3.         $("#result").html(ajax_load); 
  4.         $.post( 
  5.             loadUrl, 
  6.             {language: "php", version: 5}, 
  7. function(responseText){ 
  8.                 $("#result").html(responseText); 
  9.             }, 
  10. "html"
  11.         ); 
  12.     }); 
//	$.post()
			{language: "php", version: 5},

The use of $.post() is the same as its brother, $.get(). Check the POST request in Firebug (shown in the following image).

Finally... $.ajax():

Up to this point, we've examined five commonly used jQuery AJAX functions. They bear different names but, behind the scenes, they generally do the exact same job with slightly different configurations. If you need maximum control over your requests, check out the $.ajax() function.

This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks). -jQuery's official Documentation

In my opinion, the first five functions should satisfy most of our needs. But if you need to execute a function on AJAX error, $.ajax() is your only choice.


Today, we took an in-depth look of five ways to make AJAX calls with jQuery.

  • load(): Load a piece of html into a container DOM.
  • $.getJSON(): Load a JSON with GET method.
  • $.getScript(): Load a JavaScript.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don't want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.

Before we conclude, here's a comparison table of these functions. I hope you enjoyed this lesson! Any thoughts?

Convert Pipe Delimited File to CSV File and Choose and Reorder Columns

A friend need a small program to take a Pipe file and convert it to a CSV file. Easy enough, replace the “|”,s with “,”’s.  Until you add more requirements, allow the user to choose which columns they want to convert over and allow them to re-order the columns and save the file as something else.  Ok now you’re talking about streamreaders, streamwriter, some type or reorder control and choosing columns. Turning a 45min project into a  3 hour project going at full pace, as I’m not much of a Windows Form developer, I generally stick in the asp.net world.

Anyway.. here’s the project in VB.Net and source code.

The executable is in it’s default location TextPipeConverter\TextPipeConverter\bin\Debug\TextPipeConverter.exe

Notes: There’s no error checking, very minor, no try catches, quick and dirty.

Casting Types in VB.Net and More

Source: Cheat Sheet - Casting in VB.NET and C#

Great little find, and since I’m a VB.Net whore, I’ll just post up the VB.Net version :)

Casting in VB.NET

  1. By default in VB, casting is automatically done for you when you assign objects to variables. The objects are then automatically casted to the variables' type.

    This behavior can be influenced by an option line on top of your code file:

    Option Strict On
    Option Strict Off

    When on, casting is strict and not automatic.

  2. Explicit casting can be done with the cast operator CType() or DirectCast():

    textbox = CType(obj, TextBox)
    textbox = DirectCast(obj, TextBox)

    The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType. DirectCast throws an InvalidCastException error if the argument types do not match.

  3. Testing if an object is of a particular type, can be done with the TypeOf...Is operator:

    If TypeOf obj Is TextBox Then...
  4. Obtaining a System.Type object for a given type can be done with the GetType operator:

    Dim t As System.Type
    t = GetType(String)
  5. Obtaining a System.Type object for a given object can be done with the GetType method:

    Dim t as System.Type
    t = obj.GetType()

Now to build on and add one more of my own…

Get the type based on an arbitrary string.


Problem with this though is you can not use it to cast using CType or DirectCast. Looking at the CType Function..

typename - Any expression that is legal within an As clause in a Dim statement, that is, the name of any data type, object, structure, class, or interface.

You can only use types that are compiled and can’t use types that show up at runtime. So trying to use CType(obj, System.Type.GetType(“System.String”)) will only get you an error.  Array bounds cannot appear in type specifiers.

How to get around this? I have no freaking idea, yet. I’m think I might could create a custom type of my own and do something so that it converts to the proper method but for now I’ll just catch a few ArgumentExceptions and try different cast types then.

HTTP Error 404.17 Not Found – Using WCF .SVC Service

So you’re getting IIS error’s when trying to run a .svc file that’s coded to use WCF or Windows Communication Foundation.

HTTP Error 404.17 - Not Found

The requested content appears to be script and will not be served by the static file handler.

or maybe..

HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

Took me awhile to realize I need to setup/configure IIS and WCF properly.  Here are the steps from MS, I went through and realized I had missed one component (IIS6 Scripting tools, who would have thought), which I probably didn’t need, but the big ones that I didn’t have WCF Http Activation installed.  After that, I registered WCF..

"%WINDIR%\Microsoft.Net\Framework\v3.5\WFServicesReg.exe" /c

and then I was golden, but there might be other things you are lacking or missing. So go through all the steps.

One-Time Set Up Procedure for the Windows Communication Foundation Samples

Set the DefaultButton inside a LoginView Control in a MasterPage

Ok if you google this you’ll get some solutions that say set the DefaultButton to ParentControlID$ButtonID

However, this didn’t work for me. I kept getting the same error no matter what I tried.

The DefaultButton of '<PanelID>' must be the ID of a control of type IButtonControl.

So I tried another approach that worked great.

On page load I found the Panel Control and found the button control and set the default button programmatically.

<asp:LoginView ID="LoginView1" runat="server">
        <asp:Panel ID="pnlLogin" runat="server">
            <telerik:RadTextBox ID="tbUsername" runat="server" EmptyMessage="Username" />&nbsp;
            <telerik:RadTextBox ID="tbPassword" runat="server" EmptyMessage="Password" TextMode="Password" />&nbsp;
            <div id="SignIn" style="position: relative; z-index: 1; float: right; bottom: 21px;">
                 <asp:LinkButton ID="lbSignIn" runat="server" Font-Bold="true" Font-Size="Small" Text="SIGN IN" OnClick="lbSignIn_Click" />
            <div id="divLoginLinks" style="position:relative; clear:both">
                <span class="GrayFooterFont"><asp:HyperLink ID="hlRegister" runat="server" Text="Register" NavigateUrl="~/Registration.aspx" /> | <asp:HyperLink ID="hlForgot" runat="server" Text="Forgot Password" NavigateUrl="~/ForgotPassword.aspx" /></span>
        <small><asp:Label ID="lblLoggedInUsername" runat="server" /> | <asp:LinkButton ID="lbSignOut" runat="server" Text="SIGN OUT" OnClick="lbSignOut_Click" /></small>
        <asp:LinkButton ID="lbSignIn" runat="server" Font-Bold="true" Font-Size="Small" Text="SIGN IN" OnClick="lbSignIn_Click" CssClass="hidden" />

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'If User is not logged in do this        
    Dim pnlLogin As Panel
    Dim lbSignIn As LinkButton
    pnlLogin = CType(LoginView1.Controls(0).FindControl("pnlLogin"), Panel)
    lbSignIn = CType(LoginView1.Controls(0).FindControl("lbSignIn"), LinkButton)
    pnlLogin.DefaultButton = lbSignIn.ID
    pnlLogin = Nothing
    lbSignIn = Nothing
End Sub

I’m sure I could have just hardcoded the lblSignIn ID to the pnlLogin, but no idea why I didn’t.

Play Ripped DVD’s on Windows Media Center

For Windows Vista:

Open Registry Editor (Start, Run, REGEDIT) and navigate to:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Media Center\Settings\DvdSettings

Double-click the key ShowGallery and change the value from “Play” to “Gallery”.

For Windows 7:

Don’t need it, it’s already built this way.

jQuery Plug-In Links I’ve collected

Here some links I’ve received from friends and have run across that have some cool jQuery plug-ins that I would like to use one day.


SilverLight Reference Controls

Reference a control that’s is outside your View, or on your MainPage if you’re using NavigationFrame or your “Parent” window.

Assumption: MainPage UserControl page is your starting page and has a NavigationFrame and a View is loaded in a content window.

Method 1: (Assuming “MainPage” is the name of your MainPage or the x:Class it uses, x:Class="<AppName>.MainPage" and the TextBlock named “lblStep1”)

Dim Main As MainPage = CType(<AppName>.App.Current.RootVisual, MainPage)
        CType(Main.FindName("lblStep1"), TextBlock).Text = "Hello Test123"

Or Method 2:

CType(CType(<AppName>.App.Current.RootVisual, MainPage).FindName("lblStep1"), TextBlock).Text = "Updated Text"


Reference a Control in a User Control that’s on the same view.

  1. CType(siTest.FindName("lblStep1"), TextBlock).Text = "Testing"