jQuery: ‘The Write Less, Do More’

What is jQuery?
jQuery is a lightweight, “write less, do more”, JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code .jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities

jQuery Syntax
The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s). jQuery uses CSS syntax to select elements.

Basic syntax is: $(selector).action()

A $ sign to define/access jQuery, $ sign is a shortcut for ‘jQuery’
A (selector) to “query (or find)” HTML elements
A jQuery action() to be performed on the element(s)

Examples:
$(this).hide() – hides the current element.
$(“p”).hide() – hides all <p> elements.
$(“.test”).hide() – hides all elements with.
$(“#test”).hide() – hides the element with id=”test”.
The Document Ready Event

 $(document).ready(function(){
     // jQuery methods go here...
 });

This is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.
The jQuery team has also created an even shorter method for the document ready event:

$(function(){
    // jQuery methods go here...
});

but document ready event is easier to understand when reading the code.

jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to “find” (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more. It’s based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $(). The jQuery element selector selects elements based on the element name.
You can select all <p> elements on a page like this:

$("p")

The #id Selector
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element. To find an element with a specific id, write a hash character, followed by the id of the element:

$("#test")

The .class Selector
The jQuery class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:

$(".test")

jQuery Events
All the different visitor’s actions that a web page can respond to are called events. An event represents the precise moment when something happens.
Examples:
moving a mouse over an element
selecting a radio button
clicking on an element

click()
The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element. The following example says: When a click event fires on a <p> element; hide the current <p> element:

$("p").click(function(){
    $(this).hide();
});

dblclick()
The dblclick() method attaches an event handler function to an HTML element. The function is executed when the user double-clicks on the HTML element:

$("p").dblclick(function(){
    $(this).hide();
});

mouseenter()
The mouseenter() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer enters the HTML element:

$("#p1").mouseenter(function(){
    alert("You entered p1!");
});

mouseleave()
The mouseleave() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer leaves the HTML element:

$("#p1").mouseleave(function(){
    alert("Bye! You now leave p1!");
});

mousedown()
The mousedown() method attaches an event handler function to an HTML element. The function is executed, when the left mouse button is pressed down, while the mouse is over the HTML element:

$("#p1").mousedown(function(){
    alert("Mouse down over p1!");
});

mouseup()
The mouseup() method attaches an event handler function to an HTML element. The function is executed, when the left mouse button is released, while the mouse is over the HTML element:

$("#p1").mouseup(function(){
    alert("Mouse up over p1!");
});

hover()
The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods. The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:

$("#p1").hover(function(){
   alert("You entered p1!");
},
function(){
   alert("Bye! You now leave p1!");
});

focus()
The focus() method attaches an event handler function to an HTML form field. The function is executed when the form field gets focus:

$("input").focus(function(){
    $(this).css("background-color","#cccccc");
});

blur()
The blur() method attaches an event handler function to an HTML form field. The function is executed when the form field loses focus:

$("input").blur(function(){
    $(this).css("background-color","#ffffff");
});

jQuery Hide/Show
hide() and show()
With jQuery, you can hide and show HTML elements with the hide() and show() methods:
$(selector).hide(speed,callback);
$(selector).show(speed,callback);
The optional speed parameter specifies the speed of the hiding/showing, and can take the following values: “slow”, “fast”, or milliseconds.The optional callback parameter is a function to be executed after the hide() or show() method completes.

$("#hide").click(function(){
    $("p").hide();
});
$("#show").click(function(){
    $("p").show();
});
$("button").click(function(){
    $("p").hide(1000);
});
$("button").click(function(){
  $("p").hide("slow",function(){
    alert("The paragraph is now hidden");
  });
});

toggle()
With jQuery, you can toggle between the hide() and show() methods with the toggle() method.
$(selector).toggle(speed,callback);
The optional speed parameter can take the following values: “slow”, “fast”, or milliseconds.
The optional callback parameter is a function to be executed after toggle() completes.

$("button").click(function(){
    $("p").toggle();
});

jQuery Fade
With jQuery you can fade an element in and out of visibility. jQuery has the following fade methods:
fadeIn()
The jQuery fadeIn() method is used to fade in a hidden element.
$(selector).fadeIn(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds.The optional callback parameter is a function to be executed after the fading completes.The following example demonstrates the fadeIn() method with different parameters:

$("button").click(function(){
  $("#div1").fadeIn();
  $("#div2").fadeIn("slow");
  $("#div3").fadeIn(3000);
});

fadeOut()
The jQuery fadeOut() method is used to fade out a visible element.
$(selector).fadeOut(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds.The optional callback parameter is a function to be executed after the fading completes.The following example demonstrates the fadeOut() method with different parameters:

$("button").click(function(){
  $("#div1").fadeOut();
  $("#div2").fadeOut("slow");
  $("#div3").fadeOut(3000);
});

fadeToggle()
The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.If the elements are faded out, fadeToggle() will fade them in. If the elements are faded in, fadeToggle() will fade them out.
$(selector).fadeToggle(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after the fading completes. The following example demonstrates the fadeToggle() method with different parameters:

$("button").click(function(){
  $("#div1").fadeToggle();
  $("#div2").fadeToggle("slow");
  $("#div3").fadeToggle(3000);
});

fadeTo()
The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).
$(selector).fadeTo(speed,opacity,callback);
The required speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds. The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1). The optional callback parameter is a function to be executed after the function completes. The following example demonstrates the fadeTo() method with different parameters:

$("button").click(function(){
  $("#div1").fadeTo("slow",0.15);
  $("#div2").fadeTo("slow",0.4);
  $("#div3").fadeTo("slow",0.7);
});

jQuery Slide
With jQuery you can create a sliding effect on elements. jQuery has the following slide methods:
slideDown()
The jQuery slideDown() method is used to slide down an element.
$(selector).slideDown(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after the sliding completes. The following example demonstrates the slideDown() method:

$("#flip").click(function(){
  $("#panel").slideDown();
});

slideUp()
The jQuery slideUp() method is used to slide up an element.
$(selector).slideUp(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: “slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after the sliding completes. The following example demonstrates the slideUp() method:

$("#flip").click(function(){
  $("#panel").slideUp();
});

slideToggle()
The jQuery slideToggle() method toggles between the slideDown() and slideUp() methods.If the elements have been slid down, slideToggle() will slide them up. If the elements have been slid up, slideToggle() will slide them down.
$(selector).slideToggle(speed,callback);
The optional speed parameter can take the following values: “slow”, “fast”, milliseconds. The optional callback parameter is a function to be executed after the sliding completes. The following example demonstrates the slideToggle() method:

$("#flip").click(function(){
  $("#panel").slideToggle();
});

jQuery Animate
The jQuery animate() method is used to create custom animations.
$(selector).animate({params},speed,callback);
The required params parameter defines the CSS properties to be animated. The optional speed parameter specifies the duration of the effect. It can take the following values:  slow”, “fast”, or milliseconds. The optional callback parameter is a function to be executed after the animation completes. The following example demonstrates a simple use of the animate() method; it moves a element to the right, until it has reached a left property of 250px:

$("button").click(function(){
  $("div").animate({left:'250px'});
});

jQuery animate() – Manipulate Multiple Properties
Notice that multiple properties can be animated at the same time:

$("button").click(function(){
  $("div").animate({
    left:'250px',
    opacity:'0.5',
    height:'150px',
    width:'150px'
  });
});

jQuery animate() – Using Relative Values
It is also possible to define relative values (the value is then relative to the element’s current value). This is done by putting += or -= in front of the value:

$("button").click(function(){
  $("div").animate({
    left:'250px',
    height:'+=150px',
    width:'+=150px'
  });
});

jQuery animate() – Using Pre-defined Values
You can even specify a property’s animation value as “show”, “hide”, or “toggle”:

$("button").click(function(){
  $("div").animate({
    height:'toggle'
  });
});

jQuery animate() – Uses Queue Functionality
By default, jQuery comes with queue functionality for animations. This means that if you write multiple animate() calls after each other, jQuery creates an “internal” queue with these method calls. Then it runs the animate calls ONE by ONE.
So, if you want to perform different animations after each other, we take advantage of the queue functionality:

$("button").click(function(){
  var div=$("div");
  div.animate({height:'300px',opacity:'0.4'},"slow");
  div.animate({width:'300px',opacity:'0.8'},"slow");
  div.animate({height:'100px',opacity:'0.4'},"slow");
  div.animate({width:'100px',opacity:'0.8'},"slow");
});

jQuery Stop Animations
The jQuery stop() method is used to stop an animation or effect before it is finished. The stop() method works for all jQuery effect functions, including sliding, fading and custom animations.
$(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the animation queue should be cleared or not. Default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The optional goToEnd parameter specifies whether or not to complete the current animation immediately. Default is false. So, by default, the stop() method kills the current animation being performed on the selected element. The following example demonstrates the stop() method, with no parameters:

$("#stop").click(function(){
  $("#panel").stop();
});

jQuery HTML Get Content and Attributes
Get Content – text(), html(), and val()
Three simple, but useful, jQuery methods for DOM manipulation are:
text() – Sets or returns the text content of selected elements
html() – Sets or returns the content of selected elements (including HTML markup)
val() – Sets or returns the value of form fields
The following example demonstrates how to get content with the jQuery text() and html() methods:

$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

The following example demonstrates how to get the value of an input field with the jQuery val() method:

$("#btn1").click(function(){
  alert("Value: " + $("#test").val());
});

Get Attributes – attr()
The jQuery attr() method is used to get attribute values. The following example demonstrates how to get the value of the href attribute in a link:

$("button").click(function(){
  alert($("#w3s").attr("href"));
});

jQuery HTML Set Content and Attributes
Set Content – text(), html(), and val()
We will use the same three methods from the previous page to set content:
text() – Sets or returns the text content of selected elements
html() – Sets or returns the content of selected elements (including HTML markup)
val() – Sets or returns the value of form fields
The following example demonstrates how to set content with the jQuery text(), html(), and val() methods:

$("#btn1").click(function(){
  $("#test1").text("Hello world!");
});
$("#btn2").click(function(){
  $("#test2").html("Hello world!");
});
$("#btn3").click(function(){
  $("#test3").val("Dolly Duck");
});

A Callback Function for text(), html(), and val()
All of the three jQuery methods above: text(), html(), and val(), also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value. You then return the string you wish to use as the new value from the function. The following example demonstrates text() and html() with a callback function:

$("#btn1").click(function(){
  $("#test1").text(function(i,origText){
    return "Old text: " + origText + " New text: Hello world!
    (index: " + i + ")"; 
  });
});

$("#btn2").click(function(){
  $("#test2").html(function(i,origText){
    return "Old html: " + origText + " New html: Hello world!
    (index: " + i + ")"; 
  });
});

Set Attributes – attr()
The jQuery attr() method is also used to set/change attribute values. The following example demonstrates how to change (set) the value of the href attribute in a link:

$("button").click(function(){
  $("#w3s").attr("href","http://www.w3schools.com/jquery");
});

The attr() method also allows you to set multiple attributes at the same time. The following example demonstrates how to set both the href and title attributes at the same time:

$("button").click(function(){
  $("#w3s").attr({
    "href" : "http://www.w3schools.com/jquery",
    "title" : "W3Schools jQuery Tutorial"
  });
});

A Callback Function for attr()
The jQuery method attr(), also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) attribute value. You then return the string you wish to use as the new attribute value from the function. The following example demonstrates attr() with a callback function:

$("button").click(function(){
  $("#w3s").attr("href", function(i,origValue){
    return origValue + "/jquery"; 
  });
});

jQuery HTML Add Elements/Content
We will look at four jQuery methods that are used to add new content:
append() and prepend()
The jQuery append() method inserts content AT THE END of the selected HTML elements. The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.

$("p").append("Some appended text.");
$("p").prepend("Some prepended text.");

after() and before()
The jQuery after() method inserts content AFTER the selected HTML elements.
The jQuery before() method inserts content BEFORE the selected HTML elements.

$("img").after("Some text after");
$("img").before("Some text before");

jQuery HTML Remove Elements/Content
To remove elements and content, there are mainly two jQuery methods:
remove()
The jQuery remove() method removes the selected element(s) and its child elements.

$("#div1").remove();

empty()
The jQuery empty() method removes the child elements of the selected element(s).

$("#div1").empty();

Filter the Elements to be Removed
The jQuery remove() method also accepts one parameter, which allows you to filter the elements to be removed. The parameter can be any of the jQuery selector syntaxes. The following example removes all elements with class=”italic”:

$("p").remove(".italic");

jQuery Get and Set CSS Classes
jQuery has several methods for CSS manipulation. We will look at the following methods:
addClass()
The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:

$("button").click(function(){
  $("h1,h2,p").addClass("blue");
  $("div").addClass("important");
});

You can also specify multiple classes within the addClass() method:

$("button").click(function(){
  $("#div1").addClass("important blue");
});

removeClass()
The following example shows how to remove a specific class attribute from different elements:

$("button").click(function(){
  $("h1,h2,p").removeClass("blue");
});

toggleClass()
The following example will show how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:

$("button").click(function(){
  $("h1,h2,p").toggleClass("blue");
});

jQuery css() Method
Get a CSS Property
The css() method sets or returns one or more style properties for the selected elements.
css(“propertyname”);
The following example will return the background-color value of the FIRST matched element:

$("p").css("background-color");

Set a CSS Property
To set a specified CSS property, use the following syntax:
css(“propertyname”,”value”);
The following example will set the background-color value for ALL matched elements:

$("p").css("background-color","yellow");

Set Multiple CSS Properties
To set multiple CSS properties, use the following syntax:
css({“propertyname”:”value”,”propertyname”:”value”,…});
The following example will set a background-color and a font-size for ALL matched elements:

$("p").css({"background-color":"yellow","font-size":"200%"});

jQuery Dimensions
jQuery has several important methods for working with dimensions:
width() and height()
The width() method sets or returns the width of an element (includes NO padding, border, or margin). The height() method sets or returns the height of an element (includes NO padding, border, or margin). The following example returns the width and height of a specified element:

$("button").click(function(){
  var txt="";
  txt+="Width: " + $("#div1").width() + "";
  txt+="Height: " + $("#div1").height();
  $("#div1").html(txt);
});

innerWidth() and innerHeight()
The innerWidth() method returns the width of an element (includes padding). The innerHeight() method returns the height of an element (includes padding). The following example returns the inner-width/height of a specified element:

$("button").click(function(){
  var txt="";
  txt+="Inner width: " + $("#div1").innerWidth() + "";
  txt+="Inner height: " + $("#div1").innerHeight();
  $("#div1").html(txt);
});

outerWidth() and outerHeight()
The outerWidth() method returns the width of an element (includes padding and border). The outerHeight() method returns the height of an element (includes padding and border). The following example returns the outer-width/height of a specified element:

$("button").click(function(){
  var txt="";
  txt+="Outer width: " + $("#div1").outerWidth() + "";
  txt+="Outer height: " + $("#div1").outerHeight();
  $("#div1").html(txt);
});

The outerWidth(true) method returns the width of an element (includes padding, border, and margin). The outerHeight(true) method returns the height of an element (includes padding, border, and margin).

$("button").click(function(){
  var txt="";
  txt+="Outer width (+margin): " + $("#div1").outerWidth(true) + "";
  txt+="Outer height (+margin): " + $("#div1").outerHeight(true);
  $("#div1").html(txt);
});

More width() and height()
The following example returns the width and height of the document (the HTML document) and window (the browser viewport):

$("button").click(function(){
  var txt="";
  txt+="Document width/height: " + $(document).width();
  txt+="x" + $(document).height() + "\n";
  txt+="Window width/height: " + $(window).width();
  txt+="x" + $(window).height();
  alert(txt);
});

The following example sets the width and height of a specified element:

$("button").click(function(){
  $("#div1").width(500).height(500);
});

jQuery Traversing
jQuery traversing, which means “move through”, are used to “find” (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire.
jQuery provides a variety of methods that allows us to traverse the DOM. The largest category of traversal methods are tree-traversal. The next chapters will show us how to travel up, down and sideways in the DOM tree.
jQuery Traversing Ancestor
An ancestor is a parent, grandparent, great-grandparent, and so on.
With jQuery you can traverse up the DOM tree to find ancestors of an element.
parent()
The parent() method returns the direct parent element of the selected element. This method only traverse a single level up the DOM tree. The following example returns the direct parent element of each elements:

$(document).ready(function(){
  $("span").parent();
});

parents()
The parents() method returns all ancestor elements of the selected element, all the way up to the document’s root element ().The following example returns all ancestors of all elements:

$(document).ready(function(){
  $("span").parents();
});

You can also use an optional parameter to filter the search for ancestors.
The following example returns all ancestors of all elements that are elements:

$(document).ready(function(){
  $("span").parents("ul");
}/);

parentsUntil()
The parentsUntil() method returns all ancestor elements between two given arguments. The following example returns all ancestor elements between a and a element:

$(document).ready(function(){
  $("span").parentsUntil("div");
});

jQuery Traversing Descendants
A descendant is a child, grandchild, great-grandchild, and so on. With jQuery you can traverse down the DOM tree to find descendants of an element.
Two useful jQuery methods for traversing down the DOM tree are:
children()
The children() method returns all direct children of the selected element. This method only traverse a single level down the DOM tree. The following example returns all elements that are direct children of each elements:

$(document).ready(function(){
  $("div").children();
});

You can also use an optional parameter to filter the search for children. The following example returns all elements with the class name “1”, that are direct children of:

$(document).ready(function(){
  $("div").children("p.1");
});

find()
The find() method returns descendant elements of the selected element, all the way down to the last descendant. The following example returns all elements that are descendants of:

$(document).ready(function(){
  $("div").find("span");
});

The following example returns all descendants of:

$(document).ready(function(){
  $("div").find("*");
});

jQuery Traversing Sideways
There are many useful jQuery methods for traversing sideways in the DOM tree:
siblings()
The siblings() method returns all sibling elements of the selected element. The following example returns all sibling elements of:

$(document).ready(function(){
  $("h2").siblings();
});

You can also use an optional parameter to filter the search for siblings. The following example returns all sibling elements of that are elements:

$(document).ready(function(){
  $("h2").siblings("p");
});

next()
The next() method returns the next sibling element of the selected element.This method only returns one element. The following example returns the next sibling of:

$(document).ready(function(){
  $("h2").next();
});

nextAll()
The nextAll() method returns all next sibling elements of the selected element. The following example returns all next sibling elements of:

$(document).ready(function(){
  $("h2").nextAll();
});

nextUntil()
The nextUntil() method returns all next sibling elements between two given arguments. The following example returns all sibling elements between a and a element:

$(document).ready(function(){
  $("h2").nextUntil("h6");
});

jQuery prev(), prevAll() & prevUntil() Methods
The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).

Narrow Down The Search For Elements
The three most basic filtering methods are first(), last() and eq(), which allow you to select a specific element based on its position in a group of elements. Other filtering methods, like filter() and not() allow you to select elements that match, or not match, a certain criteria.
first()
The first() method returns the first element of the selected elements. The following example selects the first element inside the first element:

$(document).ready(function(){
  $("div p").first();
});

last()
The last() method returns the last element of the selected elements. The following example selects the last element inside the last element:

$(document).ready(function(){
  $("div p").last();
});

eq()
The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 and not 1. The following example selects the second element (index number 1):

$(document).ready(function(){
  $("p").eq(1);
});

filter()
The filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. The following example returns all elements with class name “intro”:

$(document).ready(function(){
  $("p").filter(".intro");
});

not()
The not() method returns all elements that do not match the criteria. Tip: The not() method is the opposite of filter(). The following example returns all elements that do not have class name “intro”:

$(document).ready(function(){
$("p").not(".intro");
});

jQuery and AJAX
AJAX is the art of exchanging data with a server, and updating parts of a web page – without reloading the whole page.
AJAX = Asynchronous JavaScript and XML. In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.
jQuery provides several methods for AJAX functionality.

load()
The jQuery load() method is a simple, but powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element.
$(selector).load(URL,data,callback);
The required URL parameter specifies the URL you wish to load. The optional data parameter specifies a set of querystring key/value pairs to send along with the request. The optional callback parameter is the name of a function to be executed after the load() method is completed.
The following example loads the content of the file “demo_test.txt” into a specific element:

$("#div1").load("demo_test.txt");

It is also possible to add a jQuery selector to the URL parameter. The following example loads the content of the element with id=”p1″, inside the file “demo_test.txt”, into a specific element:

$("#div1").load("demo_test.txt #p1");

The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
responseTxt – contains the resulting content if the call succeed
statusTxt – contains the status of the call
xhr – contains the XMLHttpRequest object
The following example displays an alert box after the load() method completes. If the load() method has succeed, it displays “External content loaded successfully!”, and if it fails it displays an error message:

$("button").click(function(){
  $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
    if(statusTxt=="success")
      alert("External content loaded successfully!");
    if(statusTxt=="error")
      alert("Error: "+xhr.status+": "+xhr.statusText);
  });
});

jQuery AJAX get() and post() Methods
Two commonly used methods for a request-response between a client and server
GET – Requests data from a specified resource
POST – Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server. [The GET method may return cached data.]
POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
$.get()
The $.get() method requests data from the server with an HTTP GET request.
$.get(URL,callback);
The required URL parameter specifies the URL you wish to request. The optional callback parameter is the name of a function to be executed if the request succeeds. The following example uses the $.get() method to retrieve data from a file on the server:

$("button").click(function(){
  $.get("demo_test.asp",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

The first parameter of $.get() is the URL we wish to request (“demo_test.asp”).
The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
$.post()
The $.post() method requests data from the server using an HTTP POST request.
$.post(URL,data,callback);
The required URL parameter specifies the URL you wish to request. The optional data parameter specifies some data to send along with the request. The optional callback parameter is the name of a function to be executed if the request succeeds.
The following example uses the $.post() method to send some data along with the request:

$("button").click(function(){
  $.post("demo_test_post.asp",
  {
    name:"Donald Duck",
    city:"Duckburg"
  },
  function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

The first parameter of $.post() is the URL we wish to request (“demo_test_post.asp”). Then we pass in some data to send along with the request (name and city). The ASP script in “demo_test_post.asp” reads the parameters, process them, and return a result. The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

Ref: http://www.w3schools.com/jquery/default.asp

Author : Rony T Sam

Advertisements

Encode or Decode HTML entities with jQuery

Javascript fumction for client side HTML encode and decode

function htmlEncode(value){
return $(‘<div/>’).text(value).html();
}

function htmlDecode(value){
return $(‘<div/>’).html(value).text();
}

how its works…….

The div element is created bit it is never appended to the HTML document

use of .html(): Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

use of .text(): Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

function htmlEncode: set the innerText of the element, and retrieve the encoded innerHTML
function htmlDecode: set the innerHTML value of the element and the innerText is retrieved.

Author : Rony T Sam

How to get client IP address using jQuery?

ip_logo_medjQuery gets the client IP address by just passing a url, formatted with the callback=? paramtere to the $.getJSON method.

$(document).ready(function () {
   $.getJSON("http://jsonip.com?callback=?",
     function (data) {
       var ip = (data.ip).split(',');
       $('#showIP').text('Machine IP: ' + ip[0] + 'Network IP:' + ip[1]);
  });
});

Author : Aneesh Sivan