B2B: Ajax in JQuery with special effects


Today’s article is going to cover using the excellent JQuery library to implement an AJAX username availability checker (along with a bit of eye candy to show the results). The use of visual effects with AJAX can occasionally be quite tricky, depending on what you need to do - fades by definition will take a certain period of time to execute, so you need to stagger your calls correctly to get your data fading out and back in again at the correct time (after the AJAX calls have fired).

Like the previous JQuery introduction - JQuery Pop-up Menu Tutorial - we’ll be using the latest JQuery library, and a seperate external javascript file to contain our behaviours and logic.

I’m going to skip the HTML in the hopes that you’ll actually whip up a test page yourself, and start playing around with JQuery - but obviously you need a quick description of the elements we’ll be using:

  • span with ID usernameLoading, containing an AJAX spinner.
  • a with ID usernameCheck and href of javascript:void(0)
  • span with ID usernameResult

Onto the javascript:

behaviour.js

 1  $(document).ready(function() {
 2    //username availability checker
 3    $('#usernameLoading').hide();
 4
 5    $('#usernameLoading').ajaxStart(function() {
 6      $(this).show();
 7    }).ajaxStop(function() {
 8      $(this).hide();
 9    });
10
11    $('#usernameCheck').click(function() {
12      $.post("/users/check", {
13        username: $('#UserUsername').val()
14      }, function(response){
15        $('#usernameResult').fadeOut();
16        setTimeout("finishAjax('usernameResult', '"+escape(response)+"')", 400);
17      });
18    });
19
20  });

Yep, the bulk of the action occurs in less than 20 lines of javascript (not including one function that we’ll get to now).

Starting with our standard JQuery attach function, we immediately hide the usernameLoading DIV, as this is the DIV that contains our AJAX spinner image. Lines 5 to 9 simply say that whenever an AJAX event starts and stops, the respective code should be run. This obviously only works if there is one AJAX widget on a page, so you’ll have to be clever otherwise.

Line 11 says that when our usernameCheck a element is clicked, we fire off a $.post JQuery AJAX event, to the /users/check URL, with the correct username value from the input element.

You can view other AJAX methods and examples on the library homepage.

Line 14 says that once the call has finished, pass the response through to the anonymous function which fades out the current usernameResult DIV and then calls a setTimeout on another method called finishAjax.

Line 16 could be replaced by the following two lines:

  $('#usernameResult').html(response);
  $('#usernameResult').fadeIn();

If you try the above, you’ll find that the sparkly fading in and out effect is somewhat ruined by random flickering and nonsense (at least in my Firefox) - to get around this, I use setTimeout.

 1  function finishAjax(id, response) {
 2    $('#'+id).html(unescape(response));
 3    $('#'+id).fadeIn();
 4  } //finishAjax

Be careful in passing your response text through; as you can see in line 16 of the initial listing, I escape the text and then unescape it in the finishAjax function. By waiting 400 milliseconds before replacing the inner HTML of the DIV and then fading it back in, we avoid the horrible flickering and such of the special effect.

The rest of the magic occurs at the /users/check URL - the username parameter is passed through and accessed in PHP’s $_POST array. It is then checked against the database, and depending on whether the username already exists or not, two different sets of HTML are passed back to the javascript AJAX handler.

In PHP, it’s as simple as this:

check.php

  if ($userWasInDatabase) {
    print '<strong>Username is taken already!</strong>';
  } else {
    print '<strong>Username available.</strong>';
  } //else

I think this turned out to be more of a HOWTO than a tutorial, but I think I’ll blame JQuery for that, everything just seems to happen without you having to even try hard. I also realise that I’ve skipped a lot of explanations, but I think you really need to pick up the library and play with it yourself to see how easy it is.

Share this post
  • Digg
  • StumbleUpon
  • Reddit
  • del.icio.us
  • Facebook
  • muti
  • Mixx
  • Google
  • laaik.it

This entry was posted on Wednesday, January 31st, 2007 at 12:48 am and is filed under Code, Javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

17 Responses to “B2B: Ajax in JQuery with special effects”

  1. Dom said this on

    any chance of the example files for this. Cheers

  2. shawn said this on

    I have an example of the above. It is a bit different, I was doing an example for someone, but I used some of this code and of course, gave credit :)

    http://www.shawngo.com/gafyd/index.html

  3. michael said this on

    Thanks Shawn :)

    Good idea using blur() to trigger the function.

  4. Mark said this on

    This is fantastic :) It’s going to come in very useful. Thanks!

  5. Dom said this on

    thanks shawn ;-)

  6. PFWD said this on

    Thanks this example is just what im looking for

  7. Chris Gallagher said this on

    Nice example :)

  8. Cocoliso said this on

    Thanks for sharing. Maybe link to see it in action would have been nice.

  9. Dom said this on

    would anyone be so kind as to provide a “check.php” file in ASP format ie checl.asp.

    Ive had a go at converting it but no luck at all.

    Cheers for anyone that can help.

    Dom

  10. Kevin Lim said this on

    Thanks for sharing.But I can’t see the “loading…” effect.My test code(sorry my english is very poor ):
    ==================
    demo.htm

    Ajax in JQuery with special effects

    $(document).ready(function(){
    $(”#usernameLoading”).hide();
    $(”#usernameLoading”).ajaxStart(function(){
    $(this).show();
    }).ajaxStop(function(){
    $(this).hide();
    });

    $(”#usernameCheck”).click(function(){
    $.post(”check.php”, {
    username: $(”#UserUsername”).val()
    }, function(response){
    $(”#usernameResult”).fadeOut();
    setTimeout(”finishAjax(’usernameResult’, ‘” + escape(response) + “‘)”, 400);
    });
    return false; //stop submit the form …..
    });
    });
    function finishAjax(id, response){
    $(’#’ + id).html(unescape(response));
    $(’#’ + id).fadeIn();
    } //finishAjax

    UserName:

    Submit Form !!!

    ======================
    check.php

    Username is taken already!‘;
    } else {
    print ‘Username available.‘;
    } //else
    ?>

  11. Kevin Lim said this on

    Sorry it can’t display correctly !
    (What I’ve just posted)

  12. Jonathan Holland said this on

    Dom:

    In ASP, you would do something like this:

    check.asp:

    Dim UserName
    UserName = Request.Form(”UserName”)

    if UserNameInDB(UserName) then
    Response.Write(”UserName is in Database.“)
    else
    Response.Write(”UserName is available.“)
    end if

  13. Все о jquery на одной странице :: TermiT's Blog said this on

    [...] Ajax with Special Effects [...]

  14. paul said this on

    trying to use this and for the most part great, but cannot seem to incorporate this in a way that prevents form submission. Any thoughts? I tried setting php session at the time that the check.php sends back the html, but then the form will not check that session unless the form is submitted. I don’t want to post back until form passes.

  15. joe said this on

    I got this to work. For Line 15 I had to use hide instead of fadeOut, lest I get some collision with fade outs/ins. Finally, line 16 should end with this:

    +”‘)”);

    To anyone trying this at home, don’t forget to include the finishAjax function - it’s _not_ part of jQuery. :)

  16. PFWD : blog.peterfisher.me.uk : Jquery ajaxStart ajaxStop tutorial Loading message : said this on

    [...] Read more Share These icons link to social bookmarking sites where readers can share and discover new web pages. [...]

  17. jack said this on

    How would you handle multiple ajax calls on a same page where more than one div need to be populated.
    Of course, each ajax call returns data for each specific div.

    How to show basically multiple “loading…” in each div.

    Thanks for any pointers or example.

Leave a Reply