Learning JQuery

JQuery



https://www.lynda.com/jQuery-tutorials/jQuery-Essential-Training/494389-2.html


Introduction


- Standardized, simplified way of extracting, manipulating, and creating webpage content. 

- Makes operations like retrieving data via AJAX incredibly simple

- Abstracts away a lot of browser-specific features

- Code syntax is nice and compact - code that is a lot less verbose - easier to read and maintain

- CSS syntax to find and retrieve page content. 

- Designed from the ground, up to work on sets of elements, not just individual ones

- Statement chaining

- Highly extensible - a lot of plugins available - easy to learn how to build your own plugins


jQuery-enabled page



- jQuery library is referenced by the dollar sign 

"document" keyword, indicates that we're about to perform an operation on the page itself

- ready function sets up an event listener for when the DOM structure of the page is fully parsed by the browser, and is ready to be operated on vs. the onload event, which  fires only after all of the page content, including images, have been loaded
- pass a callback function to the ready function, and this callback function is the event handler that will be fired when the ready event is triggered

- append function appends a piece of content to the tag that we passed to the jQuery function, again, in this case, that div tag

<!DOCTYPE html>
<html>

<head>
    <title>First jQuery-Enabled Page</title>
    <link rel="stylesheet" href="../style.css" />

    <!-- insert the script to reference jQuery here -->
    <script type="text/javascript" src="../jquery-3.0.0.js"></script>

    <!-- insert the script to display the Hello World message here -->
    <script type="text/javascript">
        // Inserting content using jQuery
        $("document").ready(function() {
            $("#content").append("<p>The page just loaded.</p>");
        });
        
        // Inserting content the old way using the DOM 
        window.addEventListener("DOMContentLoaded", function(evt) {
            var elem = document.getElementById("content");
            var para = document.createElement("p");
            var text = document.createTextNode("The page just loaded.");
            para.appendChild(text);
            elem.appendChild(para);
        });
    </script>
</head>

<body>
    <h1>First jQuery Page</h1>
    <div id="content">
        <!-- we start with an empty document -->
    </div>
</body>

</html>

Selectors

- Used to select parts of the Web page using a common CSS-style syntax.

-  $("p") will select all of the paragraph tags in a document and return them as a list that can be further operated upon

Filters

- Used to further refine the results returned from selectors

$("p:first") will select the first paragraph in the returned set from $("p").


<!DOCTYPE html>
<html>
<head>
    <title>Selectors and Filters</title>
    <link rel="stylesheet" href="../style.css" />
    <script type="text/javascript" src="../jquery-3.0.0.js"></script>
    <script type="text/javascript">
        $("document").ready(function() {
//            $("p").css("border", "3px solid red");
//            $(".selectors").css("border", "3px solid red");
//            $("#intro").css("border", "3px solid blue");
            $("p:first").css("border", "3px solid red");
            $("h2:not(.selectors)").css("border", "3px solid red");
        });
    </script>
</head>

<body>
    <h1 id="intro">Introduction to jQuery Selectors and Filters</h1>
    <div id="content">
        <p>Selectors and Filters provide a way of finding and extracting information from Web pages.</p>
        
        <h2 class="selectors">Selectors</h2>
        <p>Selectors are used to select parts of the Web page using a common CSS-style syntax.</p>
        <p>For example, <code>$("p")</code> will select all of the paragraph tags in a document and return them as a list that
            can be further operated upon.</p>
            
        <h2 class="filters">Filters</h2>
        <p>Filters are used to further refine the results returned from selectors.</p>
        <p>For example, <code>$("p:first")</code> will select the first paragraph in the returned set from <code>$("p")</code>.</p>
    </div>
</body>

</html>


Creating and modifying page content


- Create some new content by simply calling the jQuery function with a string of HTML

- I have a div with an ID of example - this div will have a new paragraph with some emphasized text inside of it that says hello there because the HTML function will replace all the existing HTML that's already in this element

- Prepend means take this content and insert this content in front of whatever the result of this selector is
- Text is different than the HTML function, in that it will take whatever string you give it, and convert it in to escaped text content - It won't be treated, or parsed as HTML

<!DOCTYPE html>
<html>

<head>
    <title>Creating and Changing Content</title>
    <link rel="stylesheet" href="../style.css" />
    <script type="text/javascript" src="../jquery-3.0.0.js"></script>
    <script type="text/javascript">
        $("document").ready(function () {
            // create some new content
            var newP = $("<p>");
            newP.append("<em>Hello There</em>");
//            
            $("#example").html(newP);
//            
            $("#creation").prepend("Watch This! ");
//            
//            // change the existing content
            $("#example").html("<h2>This is a new H2</h2>");
//            
            $("#example").text("<h2>This is a new H2</h2>");
        });
    </script>
</head>

<body>
    <h1 id="intro">Using jQuery to Create/Change Content</h1>
    <div id="content">

        <p>jQuery makes it very easy to create new page content and change existing page content.</p>
        <h2 id="creation">Content Creation</h2>
        <p>Creating new content is as simple as passing a string of HTML to the $() function.</p>
        <p>For example, <code>$("&lt;p&gt;")</code> creates a new, empty paragraph tag. To add new content to the paragraph,
            you could simply write <code>$("&lt;p&gt;").append("&lt;em&gt;Hello there&lt;/em&gt;")</code>.</p>
        <h2 id="changing">Changing Content</h2>
        <p>There are multiple ways to change page content using jQuery, depending on your needs.</p>
        <p>The <code>html()</code> and <code>text()</code> functions can be used to directly manipulate the contents of elements,
            and there are ways to control how content can be inserted and moved around in the page.</p>
        <div id="example">
        </div>
    </div>
</body>

</html>

Handling events


- Use the on function to start listening for an event - corresponding off function that means stop listening

- In this case - listening for mousemove, click and mouseleave events with callback functions to handle each one of these events

- In the onMouseOver callback function, it receives something called the jQuery unified event object as a parameter

<!DOCTYPE html>
<html>

<head>
    <title>jQuery Event Handling</title>
    <link rel="stylesheet" href="../style.css" />
    <script type="text/javascript" src="../jquery-3.0.0.js"></script>
    <script type="text/javascript">
        $("document").ready(function() {
            $("#example").on("mousemove", onMouseOver);
            $("#example").on("click", onMouseClick);
            $("#example").on("mouseleave", onMouseLeave);
        });
        
        function onMouseOver(evt) {
            $("#example").text(evt.type + ": " + evt.pageX + ", " + evt.pageY + "\n" +
                              "Button: " + evt.which + " Key: " + evt.metaKey);
        }
        function onMouseClick(evt) {
            $("#example").text(evt.type + ": " + evt.pageX + ", " + evt.pageY);
            $("#example").off("mousemove", onMouseOver);
        }
        function onMouseLeave(evt) {
            $("#example").text("mouseleave");
        }
    </script>
</head>

<body>
    <h1>jQuery Event Handling</h1>
    <div id="content">

        <p>jQuery normalizes an event structure across browsers and provides cross-browser consistency for properties such as
            the event name, the page coordinates of the mouse, the element where the event originated along with any other
            element related to the event, and information such as whether a meta-key or specific mouse button was pressed.</p>
        <div id="example">
        </div>
    </div>
</body>

</html>

Overview of selectors and filters


- The result of using selectors and filters to retrieve content, is an array of objects that meet the specified criteria

-.This array that comes back is not a set of pure DOM elements - It's a collection of jQuery objects that are wrapped around each of the DOM elements that provide a large number of functions and properties for further operating on the content


Basic selectors



Basic filters



$("document").ready(function() {
            //$("#example p:first").css("border", "3px solid red");
            //$("#example p:last").css("border", "3px solid red");
            //$("#example p:even").css("border", "3px solid red");
            //$("#example p:odd").css("border", "3px solid red");
            //$("#example .a:first").css("border", "3px solid red");
            //$("#example .b:even").css("border", "3px solid red");
            //$("#example p:gt(1)").css("border","3px solid red");
            //$("#example p:not(p:eq(2))").css("border", "3px solid red");
        });


Advanced selectors


  • $("parent > child"): selects "child" elements that are immediate descendants of the "parent"
  • $("ancestor descendant"): selects "descendant" elements as long as they have an "ancestor" element somewhere above them
  • $("prev + next"): selects the "next" element if it is immediately preceded by a "prev" element
  • $("prev ~ siblings"): selects all "siblings" elements that come after a "prev" element

        $("document").ready(function() {

        // The child selector "parent > child" selects "child" elements that are

        // immediate descendants of the "parent"

        //$("div > p").css("border", "3px solid red");

        

        // The descendant selector "ancestor descendant" selects "descendant" elements

        // as long as they have an "ancestor" element somewhere above them

        //$("div p.a").css("border", "3px solid red");

        

        // The next adjacent selector "prev + next" selects the "next" element if it

        // is immediately preceded by a "prev" element

        //$("ul + div").css("border", "3px solid red");

        

        // Next sibling selector "prev ~ siblings" selects all "siblings" elements that come

        // after a "prev" element
        //$("#para1 ~ p").css("border", "3px solid red");
    });


Attribute filters


- Attribute filters let you perform various tests to see if attributes are present and optionally contain certain values

$("document").ready(function() {
    //        $("p[class]").css("border", "3px solid red");
    //        $("p[id=para1]").css("border", "3px solid red");
    //        $("p[id^=para]").css("border", "3px solid red");
    // Selects all the p tags where the id attribute starts with para and the land contains en 
    //        $("p[id^=para][lang*=en-]").css("border", "3px solid red");
        });


Advanced filters


 $("document").ready(function() {
            //$("p:contains('3')").css("border", "3px solid red");
            //$("p:parent").css("border", "3px solid red");
            //$("div:has(p[class=a])").css("border", "3px solid red");
            
            //$("div p:first-child").css("border", "3px solid red");
            //$("div p:last-of-type").css("border", "3px solid red");
            //$("div p:nth-child(3)").css("border", "3px solid red");
            //$("div p:nth-child(2n)").css("border", "3px solid red");
        });

Traversing documents with jQuery




- HTML pages are organized as a tree structure

- This tree structure and the relationships between the elements are described using a standard API called the Document Object Model, or DOM, which is a W3C standard.
- JQuery provides a layer of API functions over the standard DOM that simplifies a lot of common operations

- If we have a reference to this paragraph element in the tree. The paragraph that follows this one is called the next sibling. There's a function to get it called next. The paragraph before this one is called the previous sibling,and there's a function to get that called prev
- The div tag that contains all these paragraphs is called their parent. There's a function to get that as well, called parent. There's a function to get all the parents of a given tag, as a set called parents. The div, body, and HTML tags are all parents of this paragraph. There's a function to get the parents of an element, but only until a particular tag is reached. That's called parentsUntil

 -find() searches within a given element to find elements that match a selector expression


- each() loops over a set of matched elements and calls a function for each one


<!DOCTYPE html>
<html>

<head>
    <title>Using jQuery Document Traversal</title>
    <link rel="stylesheet" type="text/css" href="../style.css" />
    <script type="text/javascript" src="../jquery-3.0.0.js"></script>
    <script type="text/javascript">
        $("document").ready(function() {
            // The children() function retrieves the immediate (that is, first-level down) child
            // elements of the matched set, excluding text nodes.
            //$("#example").children().css("border", "3px solid red");

//            var elem = $("#para1");
//            elem.prev().css("border", "3px solid red");
//            elem.next().css("border", "3px solid green");
//            elem.parents().css("border", "3px solid blue");
//            elem.parentsUntil($("body")).css("border", "3px solid blue");
            
            // use the find function to locate content within particular elements
            //$("#example").find("#para4").css("border", "3px solid red");

            // use the each function to iterate over a set of elements and operate on them
//            var leftmargin = 0;
//            var border = 3;
//            $("#example p").each(function(index, element) {
//                $(element).css("border", border+"px solid red")
//                          .css("margin-left", leftmargin);
//                border += 2;
//                leftmargin += 10;
//            });
        });
    </script>
</head>



jQuery statement chaining




- Allows you to perform several operations on a result set in just one line of code.

- Functions will get executed in order, starting on the left and going across to the right


CHALLENGE1:

// Selects the h2 tags in the products div that have a product.name class and an attribute data-type that matches the given criteria. 

            $("#products h2.product-name[data-type='mineralwater']").css("background-color", "#2982D0");
            $("#products h2.product-name[data-type='vitamin']").css("background-color", "#12500F");

            $("#products h2.product-name[data-type='proteinbar']").css("background-color", "#4E0F50");

Creating content



- There are functions for creating, copying, deleting, and moving content around

- When called with no arguments the html function simply retrieves the html content of the element that it's called on

- To create new content you pass a string of properly formatted html directly to the html function - this will replace the content of the match set of elements from this selector with the new content

- create a new html element as a jQuery object- store that aside in my new variable called newItem. Then I'm going to pass that new object directly to the html function, which I'm calling on the results of this selector

<script type="text/javascript">
        $("document").ready(function() {
            document.getElementById("create").addEventListener("click", function (evt) {
                createContent();
            });
            document.getElementById("change").addEventListener("click", function (evt) {
                changeContent();
            });
            document.getElementById("changeAll").addEventListener("click", function (evt) {
                changeAllTheContent();
            });
            // use the html() function to get the current HTML of an element
            //alert($("#example").html());
        });
        function createContent() {
            // use the html() function to change the content of the div
            $("#example").html("<p>Hi there!</p>");
        }
        
        function changeContent() {
            // set the text content of the last paragraph
            var newItem = $("<p>This is a new paragraph</p>");
            $("#para1").html(newItem);
        }
        
        function changeAllTheContent() {
            $("#example p").text("<p>This is a paragraph</p>");
        }
    </script>
  • html(str): can be used to retrieve or set the HTML content of an element
  • text(str): used to retrieve or set the text content of an element

Inserting page content







Altering page content


  • wrap(): wrap the matched elements with the specified content
  • wrapAll(): wrap content around the matched elements as a group
  • unWrap(): remove the parents from the matched elements
  • empty(): remove all the child elements from the matched elements
  • remove(): removes elements from the page, including any embedded data and event handlers
  • detach(): removes elements from the page, but maintains embedded data and event handlers
  • replaceAll(): replaces the matched elements with the specified content
  • replaceWith(): replaces matched elements with content or the results of a callback function


        //$("#example p").wrap("<div style='color:red'/>");


- The wrap function wraps content around existing content. The argument that you give to the wrap function is the content that you want to wrap around the result of this jQuery expression. This line of code, is going to select each paragraph and then wrap each paragraph inside a div whose style attribute is set to be the color red.

        //$("#example p").wrapAll("<div style='border:3px solid red'/>");



- wrapAll basically says, instead of wrapping each individual one of the elements that came back from this result set, wrap the common parent of all of these elements into this content



        //$("#example").empty();
        //$("#example p.a, #example p.b").remove();
        //$("#example p.a, #example p.b").detach();


- The empty function clears a container element of all of its content

- In the remove function - selecting two different selectors here, separated by a comma

- The remove function, removes elements from the page, including any embedded data, or event handlers that you've attached to those elements. If I tried to put those elements back, their embedded data and their event handlers would be gone.
- The main difference between detach and remove is that detach temporarily removes the content from the document, but it maintains the embedded data and event handlers, so if I wanted to put those detached elements back into the page later,any of the data and any event handlers I've attached to those elements will still be there.

 //$("<div>replaced</div>").replaceAll("#example p[id]");
        //$("#example p[id]").replaceWith("<div>replaced</div>");
        //$("#example p").replaceWith(replacementFn);
    });
    
    function replacementFn() {
        if ($(this).text().indexOf("1") != -1) {
            return "<p>This is paragraph uno</p>";
        }
        else {
            return this.outerHTML;
        }
    }


- The replaceAll function - selected divs got replaced, by this new div, that I created, which has the word replaced in it

- replaceWith -> in the case of replaceAll, you specified the selector in the argument to replaceAll and you pass it to the content that you want to be replaced with vs. In the replaceWith function, you're saying give me all of these elements, and then replace them with this one, right here

- Inside this function, the value of the this keyword, is set to be the current dom element, of the, in this case paragraph that's being operated on. Each time to this function, this keyword will refer to whatever object is currently in the loop at this set. What I'm going to write is, if $ this, so I'm going to wrap it inside the jQuery function to give me a jQuery object. That way I can do things I call jQuery functions. So I'm going to check this text, .indextOf, and I'm going to look for a particular string.

- Let's look for the string one, and that's not equal to -1, that means it was found. What I'm going to do is return the HTML that should be inserted in its place. In this case, I'm just going to write this is paragraph uno. Otherwise, if that string wasn't found, I don't want the HTML content of that element to be changed, so I'll just return this.outerHTML which is a dom standard. It just simply says, just take the HTML for the element as it currently is, and return that back, so that way nothing changes.

- replaceWith is a really powerful function - you can use it to dynamically operate an element in the document and generate content on the fly to replace what's already there

Manipulating attributes


attr and removeAttr, which are used to operate on attributes. 

- The attr function is used to read the value of an attribute, and if the attribute is not present on an element, then the result is undefined.

- When called with both an attribute name and a value, an attribute with that value is set on the element. 

- removeAttr removes the named attribute from an element


            // Add a title attribute to all of the images
            //$("a").attr("title", "Photo by some photographer");


            // Make each image open in a new window

            $("a").attr("target", "_blank");



            // Remove the href from the <a> tags, making images unclickable

            //$("a").removeAttr("href");



            // Modify multiple attributes at once
            //$("img").attr({ src: "images/Spring.jpg", title: "Spring all the things!" });


- if I pass a JavaScript object, I can specify multiple attributes to change at the same time


Working with CSS


  • css(): get or set CSS properties on the matched elements in a variety of ways
  • hasClass(className): determine whether a page element has a certain class
  • addClass(className | function): add the given CSS class to the elements in the matched set
  • removeClass(className | function): remove the given CSS class from the elements in the matched set
  • toggeClass(className | function): add or remove the given CSS class to the elements in the matched set depending on whether it is already there



        $("document").ready(function() {
            $("#setProp").click(function(evt) {
                $("#example p").css("text-decoration", "overline")
                                .css("font-size", "+=1pt");
            });

            $("#setProps").click(function(evt) {
                $("#example p").css({
                    "font-weight" : "bold",
                    "color" : "red",
                    "text-decoration" : "underline"
                });
            });

            $("#addCl").click(function(evt) {
                $("#example p").addClass("pClass");
            });

            $("#rmCl").click(function(evt) {
                $("#example p").removeClass("pClass");
            });

            $("#toggleCl").click(function(evt) {
                $("#example p").toggleClass("pClass");
            });
        });

    <style>
        .pClass {
            color: green;
            text-transform: uppercase
        }
     
    </style>

Embedding custom data


    <script>
        $("document").ready(function() {
            document.getElementById("show").addEventListener("click", function (evt) {
                // if there is any data, display it
                alert(JSON.stringify($("#example").data(), null, "  "));
            });
            document.getElementById("store").addEventListener("click", function (evt) {
                // store some arbitrary data on the DIV object
                $("#example").data("key1", 1234);
                $("#example").data("key2", "Joe Marini");
            });
            document.getElementById("remove").addEventListener("click", function (evt) {
                // clear the data from the DIV
                $("#example").removeData("key2");
            });
        });
    </script>
</head>

- The data method is used to store and retrieve data on an element via data attributes

- There's two different ways you can call the function - the first is to either supply a key value pair in which case the key is the name of the attribute that will hold the data, and the value is the data itself

- Or, you can pass in a JavaScript object,which contains multiple keys and multiple values to store all at once

- To retrieve the data, you simply call the data function with the name of the key, or with no parameters at all, in which case it will return a JavaScript object containing all of the data that's currently on the element

jQuery event handling features





 $("#evtTarget").on("mouseover mouseleave", highlight);

            $("#evtTarget").on("click", function(evt) {
                $("#evtTarget").off("mouseover mouseleave", highlight);
                $("#evtTarget").html("<p>You shut off the hover effect!</p>");
                $("#evtTarget").removeClass("highlighted");
            });
            
            $("#textEntry").on("keypress", function(evt) {
                $("#keyPress").text(String.fromCharCode(evt.charCode));
            });
        });

        function highlight(evt) {
            $("#evtTarget").toggleClass("highlighted");        
        }

Event helper features


- There are a whole bunch of shorthand methods for handling form events, like form submission, and focus changes, key presses, mouse events, etc.

$(function() {
            $("#evtTarget").hover(highlight, highlight);

            $("#evtTarget").click(fnClick1);
            
            $("#evtTarget").dblclick(fnClick2);
            
            $(window).resize(fnResize);

            $("#evtTarget").one("click", function() {
                $(this).css({ borderWidth: "4px",
                    cursor: "pointer"
                });
            });
        });
        
        function highlight(evt) {
            $("#evtTarget").toggleClass("highlighted");
        }
        function fnClick1() {
            $("#evtTarget").html("Click");
        }
        function fnClick2() {
            $("#evtTarget").html("Double Click");
        }
        function fnResize() {
            $("#evtTarget").html("Browser window resized");

- One means, attach a handler that will only be executed one time for a given event type. So inside the one function I'm gonna say click, and then I'll use an anonymous function here. And the anonymous function's going to say $. This, because the this keyword is set to the element that the event happened on, in this case it was the mouse click. So I'll say this.css, and I'm going to change the border width to four pixels, and I'm going to change the cursor to the pointer.

  • hover(): use this instead of mouseover and mouseleave events
  • click(): listens for click events
  • dblclick(): listens for double-click events
  • resize(): fired on the window object when the browser window resizes

Hiding and showing elements


        $(function() {
            $("#show").click(function() {
                $("#theDiv").show("normal");
            });
            $("#hide").click(function() {
                $("#theDiv").hide(1000, "swing");
            });
            $("#toggle").click(function() {
                $("#theDiv").toggle("slow", completion);
            });
        });
        
        function completion() {
            // the value of this is set to the DOM element being affected
            $(this).text("Animation complete");
        }


  • show(): Reveals the matched elements using an optional animation
  • hide(): Hides the matched elements using an optional animation
  • toggle(): Toggles the visible state of the matched elements using an optional animation

Fading elements


  • fadeIn() fades the element in from being invisible
  • fadeOut() fades the element out and removes it from layout
  • fadeTo() fades the element to a specified opacity



        $(function() {

            $("#fadein").click(function() {

                $("#theDiv").fadeIn("normal");

            });

            $("#fadeout").click(function() {

                $("#theDiv").fadeOut("normal");

            });
            $("#fadeto3").click(function() {
                $("#theDiv").fadeTo("slow", 0.3);
            });
            $("#fadeup").click(function() {
                $("#theDiv").fadeTo("slow", 1.0, onComplete);
            });
            $("#pulse").click(function() {
                $("#theDiv").fadeTo("fast", 0.3)
                            .fadeTo("fast", 1.0)
                            .fadeTo("fast", 0.3)
                            .fadeTo("fast", 1.0);
            });
        });
        
        function onComplete() {
            $(this).text("Fading effect complete");
        }


Sliding elements


 $(function() {
            $("#slideup").click(function() {
                $("#theDiv").slideUp(1000);
            });
            $("#slidedown").click(function() {
                $("#theDiv").slideDown(200);
            });
            $("#toggle").click(function() {
                $("#theDiv").slideToggle("slow");
            });
        });

  • slideUp(): animates the height of the matched elements to 0 (or whatever CSS min-height is set to). When the animation finishes, the display CSS property of the element is set to 'none' to remove the element from the page layout
  • slideDown(): animates the height of the matched elements to reveal them
  • slideToggle(): toggles the state of the matched elements, either sliding them up or down depending on their current state

Custom animations




 <script type="text/javascript">
        $(function() {
            $("#right").click(function() {
                $("#theDiv").animate({ width: "500px" }, 1000);
            });
            $("#text").click(function() {
                $("#theDiv").animate({ fontSize: "24pt" }, 1000);
            });
            $("#move").click(function() {
                $("#theDiv").animate({ left: "500" }, 1000, "swing");
            });
            $("#all").click(function() {
                $("#theDiv").animate({ left: "500", fontSize: "24pt", width: "500px" }, 1000, "swing");
            });
        });
    </script>
    <style type="text/css">
        #theDiv {
            position: relative;
            width: 250px;
            height: 180px;
            margin: 10px;
            padding: 20px;
            background: #b3c8d0;
            border: 1px solid black;
            font-size: 16pt;
            cursor: pointer;
            left: 100px;
        }


- You can also specify a plus equal sign in front of the value that you're animating to -animate from whatever the value currently is, and then add that value to it. So I'm going to change the left part of the animation to read plus equals 500. So the left starts out at zero, and I'm going to add 500 to it. If the left was already at 100, then this would animate it up to 600 for example. 


jQuery and AJAX


- The way that the basic Ajax function works is that you use it to make a request to a server and get a response back

- $.ajax, is the global Ajax function, and then I'm going to pass in an object with a set of properties - the first parameter is the URL, and this is the path to the URL of the data that we want to retrieve - next property I'm going to supply is the type, and it's usually either going to be a Get or a Post.
- Get requests are usually used when you don't change any data on the server. You're just retrieving information. If I was changing data on the server, I would use Post instead

- Next property is the type of data that I expect to get back, and in this case, I'm expecting to get text data back - dataType, and that's going to be "text."

- Specify what happens when things succeed and fail - do that by defining some callback functions

- "success," is the success function, "error," is the error function, "complete" that's going to take two parameters, one's called xhr, and one's called status that has a "console.log("The request is complete")

- The Complete function will always be called in both cases, whether things went right or whether things went wrong. In this case, it's just an inline, anonymous Callback function. 

  <script type="text/javascript">
    $("document").ready(function() {
        getData();
      });
      
      function getData() {
        $.ajax({
          // the URL for the request
          url: "testdata.txt",

          // whether this is a POST or GET request
          type: "GET",
         
          // the type of data we expect back
          dataType : "text",
          
          // function to call for success
          success: successFn,

          // function to call on an error
          error: errorFn,
                           
          // code to run regardless of success or failure
          complete: function( xhr, status ) {
            console.log("The request is complete!");
          }
        });
      }
      
      function successFn(result) {
        console.log("Setting result");
      $("#ajaxContent").append(result);
      }
      function errorFn(xhr, status, strErr) {
        console.log("There was an error!");
      }
  </script>


Convenience functions


<script type="text/javascript">
        $("document").ready(function() {
            getData();
        });
        
        function getData() {
            // use the get() shorthand method to request a resource
            $.get("testdata.txt", successFn);
            
            // the load() shorthand method performs the common task of retrieving HTML content
            // and inserts the returned content into the specified element. 
            //$("#content").load("testdata.html");
            
            // you can also specify a portion of the content to load
            //$("#content").load("testdata.html #p2");
        }

        function successFn(result) {
            console.log("Setting result");
            $("#ajaxContent").append(result);
        }
        function errorFn(xhr, status, strErr) {
            alert(strErr);
        }
    </script>


Working with different data types


- getXMLData is being called when the document loads - dollar sign get and testXMLData.xml, and for the success function, I'll just use an anonymous function.

- Now when the success function gets called, in this case it's an anonymous inline function, this result parameter will be a parsed XML document - use the standard XML DOM functions to get data out of that XML document - like var title equals result.getElementsByTagName, and there's only one of those, so I'll get the zero index - So I've got the title, now I'll get the name, and once again, it's very similar, and so one of those. Now I'll declare a string variable, and what I'm going to do is get the title.firstChild, which is the text node inside the tag. I'll get the node value from there. Plus by plus name.firstChild.nodeValue. And then, once I have that string built, I'm going to put it into the ajaxContent div.

- getJSON is similar to the get function, only it's specifically designed to work with JSON data - when the success function gets called, the result parameter in the case of JSON will be a JavaScript object - result.items array is going to contain all of the images, and I'm going to declare a function, and remember the callback function that's given to each takes two parameters, the index of the current element, and the object itself - create a new image tag, and I'm going to set its attribute, the source attribute, to be the current item.media.m. That's the property that Flickr uses to specify the image.url.
And then I'll call .appendTO. So I'm going to append this newly created image to the ajaxContent div. And then I'm going to get a whole bunch of images back, and I don't want to list them all, so let's just stop this loop if i reaches the number four


 <script type="text/javascript">
        $("document").ready(function() {
            //getXMLData();
            getJSONData();
        });

        function getXMLData() {
            $.get("testxmldata.xml", function(result) {
                var title = result.getElementsByTagName("title")[0];
                var name = result.getElementsByTagName("name")[0];
                var val = title.firstChild.nodeValue + " by " + name.firstChild.nodeValue;
                $("#ajaxContent").append(val);
            });
        }

        function getJSONData() {
            var flickrAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
            $.getJSON( flickrAPI, {
                tags: "space needle",
                tagmode: "any",
                format: "json"
                },
                successFn);
        }

        function successFn(result) {
            $.each(result.items, function(i, item) {
                $("<img>").attr("src", item.media.m).appendTo("#ajaxContent");
                if (i === 4) {
                    return false;
                }
            });
        }

        function errorFn(xhr, status, strErr) {
            alert(strErr);
        }
    </script>


Using global AJAX handlers




- jQuery AJAX module provides a set of global event handlers that you can use to register functions to listen for interesting events that take place during the life cycle of all the AJAX requests on a given page. There are a number of scenarios where this approach might make sense.To take one example, you might want to centralize all of your error handling code in one place, rather than attach individual error handling functions to each one of your requests.
- jQuery gives you a way to intercept every request before it goes out, so that you can do things like modify or attach information to the request.

- You could even use this functionality to providesome user interfacing information. Such as a loading animation that appears and disappears when server requests start and end. All of these scenarios can be addressed using the global AJAX events.


Comments