jQuery Makes Ajax Easy, Part 1

August 3rd, 2007 by bill · 22 Comments

»Ajax programming with the jQuery Javascript library, covering load, get, post, and ajax methods. A PHP URL proxy is shown.

 

jQuery Ajax


jQuery
, John Resig’s Javascript library, makes Ajax easy for beginners and professionals alike. This article dives into using the various jQuery Ajax methods.

Ajax Basics

Asynchronous JavaScript and XML, or Ajax, has become a catch-all term for client-initiated communications with a server. Specifically, Ajax usually refers to requests sent from a web browser to a server. It is even used to refer to non-XML communications, such as Asynchronous HTML and HTTPAHAH. The rationale being that the first H in AHAH really means XHTML. I think someone just wanted another clever-sounding acronym; it really should be AJAH since it still uses Javascript. But I digress.

Simply put, Ajax allows you to execute a POST or GET request from the browser back to your server to fetch data, save data, execute a method, or what have you, without requiring a refresh of the web page.

jQuery Ajax Methods

jQuery provides several methods to assist with Ajax programming: load, get, post, and ajax.

load() takes a url, parameters, and a callback function. It executes a GET request of the URL and inserts the returned data into the DOM at a location you select. The parameters and callback function are optional. A typical usage would be something like $("address").load( url, {name:"John",id:"100"}, function(){ alert("Ajax call complete.");}).

get() takes a url, parameters, and a callback function. It executes a GET request of the URL and returns the XMLHttpRequest. The parameters and callback function are optional. A typical usage would be something like $.get( url, {name:"John",id:"100"}, function(data){ $("address").html( data ); alert("Ajax call complete.");}).

post() takes a url, parameters, and a callback function. It sends a POST request to the URL and returns the XMLHttpRequest. The parameters and callback function are optional. A typical usage would be something like $.post( url, {name:"John",id:"100"}, function(data){ $("address").html( data ); alert("Ajax call complete.");}).

ajax() takes a set of request properties specified in key-value pairs. It sends the specified request and returns the XMLHttpRequest. The ajax() method is complex but offers much more control over the request than any of the other methods. A typical usage would be something like $.ajax({ type:"GET", url:url, datatype:"html", data:{name:"John",id:"100"}, complete:function( data ) { $("address").html( data ); alert( "Ajax call complete.")}}).

Get Data From A URL

This example is taken from the jQuery Introduction posted here about a month ago. Technically, this is AJAH, since we’re not fetching XML, but the technique is the same.

We need a proxy to fetch data from another domain.

In the diagram below, you can see that the web page in your browser needs to fetch from the same domain from which it was loaded, in this case techrageo.us. From there it can go anywhere. In this example we’re fetching from Yahoo.com.

Ajax needs a URL proxy

Ajax is usually limited to connections back to the same domain from which the web page was loaded. To fetch data from another domain, such as from the Yahoo quote server, we need to create a simple URL proxy. The PHP code is below. Basically it takes a URL, fetches it with curl, and returns the output.

Note: due to server restrictions, the curl_exec string below had to be tweaked to get it into this article. Just remove the spaces and you’re good to go.

<?php
// don't cache this page
header("Cache-Control: no-cache");
function geturl($url){
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  // make this curl_exec, no spaces
  $results = c u r l _ e x e c ($ch);
  curl_close($ch);
  return $results;
}
// get the specified url from the querystring
$theurl = $_GET["url"];
// decode it
$theurl = urldecode($theurl);
// decode forgets the ampersand
$theurl = str_replace( "&#038;", "&", $theurl );
// fetch the url
$v = geturl( $theurl );
// spit out the results
echo $v;
?>

Enter a stock ticker symbol, such as IBM or SBUX, and click Submit. When you do the span with id=”lasttrade” is loaded with data returned from geturl.php?http://finance.yahoo.com/d/quotes.csv?f=l1&s=IBM (assuming you entered IBM).

Update: Yahoo has changed their quote URLs to something like this http://download.finance.yahoo.com/d/quotes.csv?f=l1&s=IBM

Ticker Symbol:

Last Trade:

We’re using .load() for this simple example.

The jQuery code is below. As you can see an anonymous function is attached to the submit handler of the form with an id of stockform. The function gets the value of the input field with an id of sym, then appends it to the URL of the Yahoo csv quote server with format specified to return the last trade price. That URL is then escaped and appended to geturl.php?url=, which is a simple PHP proxy that resides here at techrageo.us. The submit handler function then returns false to prevent the browser from trying to continue submitting the form.

// wait till the DOM is loaded
$(document).ready(function() {
  // attach a submit handler to the form
  $("form#stockform").submit(function(){
    // get the ticker symbol and build URL
    var sym = $("input#sym").val();
    var yurl = "http://download.finance.yahoo.com/d/quotes.csv?f=l1&s="+sym;
        //old: "http://finance.yahoo.com/d/quotes.csv?f=l1&s="+sym;
    var furl = "geturl.php";
    // load last trade price from Yahoo and
    // stick it in the #lasttrade span
    $("span#lasttrade").load( furl, {url:escape(yurl)} );
    return false;
  });
});

Now let’s modify the example to use $.get().

jQuery’s $.get() method can be used to send a GET request. For example, the example above can be written as follows.

// wait till the DOM is loaded
$(document).ready(function() {
  // attach a submit handler to the form
  $("form#stockform").submit(function(){
    // get the ticker symbol and build URL
    var sym = $("input#sym").val();
    var yurl = "http://download.finance.yahoo.com/d/quotes.csv?f=l1&s="+sym;
        //old: "http://finance.yahoo.com/d/quotes.csv?f=l1&s="+sym;
    var furl = "/code/geturl.php";
    $.get( furl,
      {url:escape(yurl)},
      function(data){
        $("span#lasttrade").html( data );
      });
    return false;
  });
});

Now let’s modify the example to use $.ajax() for more control.

jQuery’s $.ajax() method can also be used to send a GET request. For example, the example above can be written as follows.

// wait till the DOM is loaded
$(document).ready(function() {
  // attach a submit handler to the form
  $("form#stockform").submit(function(){
    // get the ticker symbol and build URL
    var sym = $("input#sym").val();
    var yurl = "http://download.finance.yahoo.com/d/quotes.csv?f=l1&s="+sym;
        //old: "http://finance.yahoo.com/d/quotes.csv?f=l1&s="+sym;
    var furl = "/code/geturl.php";
    $.ajax({
      url:furl,
      data:{ url:escape(yurl) },
      dataType:"html",
      success:function(data){ $("span#lasttrade").html( data );},
      error:function(xhr,err,e){ alert( "Error: " + err ); }
    }); // $.ajax()
    return false;
  }); // .submit()
});

In part 2 we’ll look at POST requests and other dataTypes.

Tags: Javascript · Programming

 

22 responses so far ↓

  • 1 Grant // Aug 3, 2007 at 10:08 am

    Nice post. I’m looking forward to the next segment.

  • 2 ronald // Sep 30, 2007 at 11:17 pm

    jquery really do everything… hey you have a nice post for this…

    really need this for my new project

  • 3 Anon // Feb 29, 2008 at 3:27 am

    Update your code/url to the yahoo website!

    Its outdated! Hence making it difficult to learn from this article!!

  • 4 bill // Feb 29, 2008 at 9:21 am

    @Anon from somewhere.com – thanks for the heads-up. I’ve updated the article. Looks like they changed from finance.yahoo.com to download.finance.yahoo.com about a month after this article was written.

  • 5 frank // Apr 23, 2008 at 11:39 am

    This is cool but why does RVBD, GILD and HANS have no price? But the others I try have a price.

  • 6 bill // May 2, 2008 at 12:23 pm

    @frank – I’m not sure. GILD works but the other two do not. Curious.

  • 7 Hyder // Feb 6, 2009 at 5:01 pm

    Hey,
    Great article, but It dont work in Firefox (v2 or v3)?

    Only for IE?

  • 8 paul // Mar 15, 2009 at 11:12 am

    Yeh dont work in firefox 2.0.0.2
    Ajax is useless. I mean what’s the point? its still not cross browser compatible. It’s not just jquery! dojo prototype and mootools don’t work cross browser.
    That why we moved to accessible sites in the first place

  • 9 bill // Mar 19, 2009 at 7:16 am

    Ajax works in most situations and provides functionality that is unavailable without Flash or some other plugin.

  • 10 Phillip // Mar 21, 2009 at 8:09 pm

    Wait, what? Hyder? Paul? Are you guys idiots? AJAX is cross browser…

    I just wrote some jQuery ajax about 10 minutes ago which works on Firefox 2/3, Opera 9+, IE6+. (and probably safari but that browser sucks more than IE).

  • 11 Anders Levin // Apr 3, 2009 at 7:03 am

    Phillip. I am also one of those who cannot get jQuery AJAX to work in Firefox.

    This should work fine no?
    $(‘#mydiv’).load(‘http://www.bash.org’);

    But it doesn’t work in Firefox, only IE. Using jQuery 1.3.2. Feel free to contact me and tell me what I am doing wrong.

  • 12 Anders Levin // Apr 3, 2009 at 7:42 am

    Well… turns out this is because of some security-issue that the Firefox team felt a need for in FF 3, however, to me it’s just a big pain in the ass. Back to IE-only webpages. See http://ajaxian.com/archives/cross-site-xmlhttprequest-in-firefox-3

  • 13 Josh Pace // Jul 15, 2009 at 1:17 pm

    Hmm, it seems that some are confusing “cross-site” and “cross-browser”. Anders seems to be trying to perform a cross-site function by using jQuery’s ajax call to load a webpage from another domain… This could be a major security vulnerability and it’s good for FF to crack down on that. To Phillip’s point, jQuery is “cross-browser” in that all of the major browsers will excute the code (as long as you’re not trying to cross-site)…

  • 14 Onur // Jan 24, 2010 at 9:56 am

    This is cool but why does RVBD, GILD and HANS have no price? But the others I try have a price.

  • 15 pihentagy // Mar 19, 2010 at 8:31 am

    Do not use escape to escape URI.

    Use encodeURI() for that purpose

  • 16 Lam Nguyen // Apr 19, 2010 at 5:18 am

    Thanks for your help…I really need the this one to work…Thanks again!

  • 17 Chuck // May 3, 2010 at 1:25 pm

    Why do you think furl should be necessary? Why do you think it wouldn’t work to submit the get/load with the download.finance.yahoo.com directly? Does it have to do with the content-disposition headers on Yahoo’s response?

  • 18 bill // May 3, 2010 at 3:30 pm

    It has to do with the inability for a client to load from a site different than the hosting site. It’s a security thing.

  • 19 G // Aug 17, 2010 at 8:52 pm

    WHERE IS part 2 anyway?

  • 20 Abe Petrillo // Aug 29, 2010 at 4:26 pm

    Excellent post! Has help my understanding 10 fold. I’ve been looking for a guide like this for some time.

    Much Appreciated!

  • 21 Mario // Oct 30, 2010 at 8:19 am

    Just wanted to comment that instead of escape, you should use encodeURIComponent in your javascript code. Otherwise, if you pass multiple symbols, they are separated by the ‘+’ character, which is converted to whitespace in the process, and then the yahoo request fails.

  • 22 Using jQuery to call Asp.net Page Method : GenerationWeb // Jan 25, 2011 at 11:54 am

    [...] more… [...]

Leave a Comment


6 − five =