Ajax Introduction

AJAX stands for Asynchronous JavaScript and XML. It is a complete game changer when it comes to user experience. Normally, web pages are loaded one at a time. When a user wants more content, they click a link. With AJAX, a user can click something and content can be loaded into the page, using JavaScript, without reloading the entire page.

Essentially, the user does some event that fires off an AJAX HttpRequest after an XMLHttpRequest object has been created. The server then processes the HttpRequest, and returns the data back to the browser. Now without JavaScript, it would be entirely worthless unless you were posting data to a database. We will set up our AJAX so it calls a JavaScript function, known as a Callback Function, to use our returned data from the server in the next tutorial.

Why Use jQuery Instead?

Learning AJAX is a great feat for any developer, but when it comes to developing, it is usually best to keep it simple. jQuery already has methods of JavaScript functions that do almost everything AJAX can do. What’s the point in rewriting long code that is already available to you? There isn’t. So, if you really love the fundamental understanding of programming read the AJAX tutorials. If not, read the AJAX tutorial under jQuery.

jQuery With HTML

We haven’t really changed any HTML elements just yet. Well now, we are here. jQuery simplifies about anything you want to do with HTML elements. jQuery’s primary purpose is to modify a web document’s HTML and CSS files, but how do we actually change HTML elements. We can insert new elements, remove elements, or even edit them using jQuery’s selectors that you read about earlier.

Generally when using jQuery with the intent to change the styling of an element, you want to do one of two things: add/remove a class to it or just change one CSS property. I would argue that it is a much better practice to always add or remove class, even if it is just one property, to/from an element. The reason being that classes are easily selected, but CSS properties require more work.

However, you can also use jQuery to modify the content of an element. You can append items before, after, or inside an element. I will show an example of modifying the entire content, but feel free to play around with these selectors and jQuery functions because they truly are a great asset to any web developer.

Example
<button id="button1">Click Me!</button>
<p id="someId">Something</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#button1").click(function()
    {
        $("#someId").html("Something Else");
    });
</script>

Common HTML Methods

  • addClass() – adds a class to the selected element
  • after() – adds content after the selected element
  • append() – adds content at the end selected element
  • attr() – adds an attribute to the selected element
  • before() – adds content at the before the selected element
  • html() – sets or gets the contents the selected element
  • remove() – removes the selected element
  • removeClass() – removes a class of the selected element
  • replaceWith() – replaces selected element with new content

Those are just a few common methods to edit HTML elements. Of course, you can always use jQuery’s references.

jQuery With CSS

jQuery makes working with CSS a breeze. The method here is .css(), and it is used very much like the other methods or actions in jQuery. While this entire tutorial will go against my conventional logic of only appending or removing classes, many of you will do it this way because it is much more simple. I must admit that it is a very quick and efficient way of applying CSS properties to an HTML element. Please just don’t paint yourself in a corner using the css method after a selector more than a few times on a single element.

The jQuery CSS Method has three different structures for its 3 different arguments.

  • .css(name) – returns the CSS property of the value
  • .css(name,value) – sets a CSS property
  • .css({properties}) – sets multiple CSS properties

We will use the first two in this example.

Example
<div id='firstDiv' style="width:150px; background-color:#D2BA0D;color:#000000;">firstDiv</div>
<div id='secondDiv' style="width:30px; background-color:#238B0A;color:#000000;">SecondDiv</div>
<input id='buttonOneId' name="buttonOne" type="button" value="Do Something!"/>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#buttonOneId").click(function()
    {
        var firstWidth = $('#firstDiv').css('width');
        $("#secondDiv").css("width",firstWidth);
    });
</script>

It is really just that simple. If you have ever had 2 or 3 divs inside 1 containing div, you know how hard it is to make all of the columns the same height or width. With JQuery, it is really just that simple. Of course, if you won’t usually use a button to change CSS in that way, but you still may find yourself using events to change CSS for some other good reason. It would get very tedious if you wanted to change large amount of CSS properties, which is why we have the third syntax of the css() method.

Example
<div id='thirdDiv' style="width:150px; height:40px; background-color:#FDE80B;color:#000000;">firstDiv</div>
<div id='fourthDiv' style="width:30px; background-color:#238B0A;color:#000000;">SecondDiv</div>
<input id='buttonTwoId' name="buttonTwo" type="button" value="Do Something!"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#buttonTwoId").click(function()
    {
        var thirdWidth = $('#thirdDiv').css('width');
        var thirdHeight = $('#thirdDiv').css('height');
        var thirdBG = $('#thirdDiv').css('background-color');
        $("#fourthDiv").css({"width":thirdWidth,"height":thirdHeight,"background-color":thirdBG});
    });
</script>

jQuery Effects

The effects used in jQuery are probably the cool effects that you have seen on others’ websites. They are extremely powerful and actually require a sizable amount of JavaScript if you were to write it without using the jQuery effects. It is important to understand how these effects work so that you have a greater knowledge of JavaScript. Often, we find ourselves looking for the easy solution, but in fact, it is usually the hard way that teaches us the lessons and concepts that we should know.

If you saw the example in the events, our example will look very familiar.

Example
<button id="button1">Hide</button>
<button id="button2">Show</button>
<ul id="someList">
    <li>
        Item 1
    </li>
    <li>
        Item 2
    </li>
</ul>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $("#button1").click(function()
    {
        $('#someList li:first').hide();
    });
    $("#button2").click(function()
    {
        $('#someList li:first').show();
    });
</script>

Pretty awesome, huh? We are using the different ids of the buttons to run the jQuery function that we want. We use two effects here, hide and show to change the visibility of the first <li> in our <ul> with an id of someList. Obviously, the hide effect is the one that makes the element invisible, and the show effect makes the element visible.

More Common Effects

  • animate() – changes a set of CSS properties with the option to animate the changes.
  • fadeIn() – animates the element from hidden to visible
  • fadeOut() – animates the element from visible to hidden
  • slideDown() – animates the change of the elements height from hidden to visible
  • slideUp() – animates the change of the elements height from visible to hidden
  • toggle() – alternatives between show and hide effects

One quick note here. We could have only used one button in the example above if we used toggle instead of hide and show. Remember, effects are your friend. Also, don’t forget to use jQuery’s official reference guide at jQuery Effects.

jQuery Selectors

Selectors are required in every statement using jQuery. The point of a selector is to select the element on which to perform an action. Selectors can select almost anything you want, from CSS styles to HTML elements. Enough talking, let’s look at some examples.

Common Selectors

  • $(“p”) – selects all of the <p> elements
  • $("[href]") – selects all of the elements with an href attribute
  • $(":textbox") – selects all of the <textbox> elements
  • $(“#someId”) – selects all of the elements where the id = “someId”
  • $(“.someClass”) – selects all of the elements where the class = “someClass”
  • $(“p#someId”) – selects all of the <p> elements where the id = “someId”
  • $(“p.someClass”) – selects all of the <p> elements where the class = “someClass”
  • $("p:first") – selects the first <p>
  • $("ul li:first") – selects the first <li> element of the <ul>
  • $(":even") – selects all of the even elements (useful in tables, lists, etc.)
  • $(":odd") – selects all of the odd elements (useful in tables, lists, etc.)

These are just a few of the selectors that jQuery contains. For a full list of selectors, visit jQuery Selectors.

As you can see with the selectors above, it is always a good idea to plan your HTML and CSS to use jQuery. It is possible for you to edit your styles and elements after the fact, but it is not ideal. Try implementing ids and classes into your HTML and CSS before you start with your jQuery. You will thank yourself for it.