Welcome To Jquey Course
Heys Geeks Welcome Back to CODOLEARN JQUREY Language
JQUERY Introduction
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS
document, or more precisely the Document Object Model (DOM), and JavaScript.
Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event
handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.
jQuery is widely famous with its philosophy of “Write less, do more.” This philosophy can be
further elaborated as
three concepts:
Basic syntax for any jQuery function is:
Why jQuery?
- It is incredibly popular, which is to say it has a large community of users and a healthy amount
of contributors who participate as developers and evangelists.
- It normalizes the differences between web browsers so that you don’t have to.
- It is intentionally a lightweight footprint with a simple yet clever plugin architecture.
- Its repository of plugins is vast and has seen steady growth since jQuery’s release.
- Its API is fully documented, including inline code examples, which in the world of JavaScript
libraries is a luxury. Heck, any documentation at all was a luxury for years.
- It is friendly, which is to say it provides helpful ways to avoid conflicts with other
JavaScript libraries.
Now we will discuss abput the advantages of jquery
- Wide range of plug-ins. jQuery allows developers to create plug-ins on top of the JavaScript
library.
- Large development community
- It has a good and comprehensive documentation
- It is a lot more easy to use compared to standard javascript and other javascript libraries.
- JQuery lets users develop Ajax templates with ease, Ajax enables a sleeker interface where
actions can be performed on pages without requiring the entire page to be reloaded.
- Being Light weight and a powerful chaining capabilities makes jQuery more strong.
the disadvantages of jquery
- While JQuery has an impressive library in terms of quantity, depending on how much customization
you require on your website, the functionality may be limited thus using raw javascript may be
inevitable in some cases.
- The JQuery javascript file is required to run JQuery commands, while the size of this file is
relatively small (25-100KB depending on the server), it is still a strain on the client computer
and maybe your web server as well if you intend to host the JQuery script on your own web
server.
jQuery | Syntax
It is used for selecting elements in HTML and performing the action on those elements.
$(selector).action()
- $ sign: It grants access to jQuery.
- (selector): It is used to find HTML elements.
- Used to hide the current element.
$(this).hide()
- Used to hide all <p> elements.
$("p").hide()
- Used to hide all elements with class=”codolearn”.
$(".codolearn").hide()
- Used to hide the element with id=”codolearn”.
$("#codolearn").hide()
Document Ready Event:
- jQuery Methods are inside a Document ready event for easy reading of code
$(document).ready(function(){
// jQuery code
});
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.
Here are some examples of actions that can fail if methods are run before the document is fully
loaded:
- Trying to hide an element that is not created yet
- Trying toget the size of an image that is not loaded yet
Selector and Events in jQuery
jQuery is a powerful JavaScript library. It is more powerful than the JavaScript. The codes of
jQuery are more precise, shorter and simpler than the standard JavaScript codes. It can perform a
variety of functions.
In this article, we will learn about jQuery selectors, jQuery Event methods and some useful methods.
jQuery selectors
jQuery selectors are used to select the HTML element(s) and allows you to manipulate the HTML
element(s) in a way we want. It selects the HTML elements on a variable parameter such as their
name, classes, id, types, attributes, attribute values, etc. All selectors in jQuery are selected
using a special sign i.e. dollar sign and parentheses:
$('selector name')
- Element selector:
The jQuery element selector selects elements based on the element name.
You can select all <h1> elements on a page like this:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<h1>
CODOLEARN LEARN TO CODE FOR FREE</h1> <br>
<button>
Hide</button> <script type="text/javascript">
$("button").click(function () {
$("h1").hide();
});
</script>
</body>
</html>
Try It Yourself »
<br>
<li>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 HTML
element:
$('#idselector');
Try It Yourself »
$(document).ready(function(){
$("button").click(function(){
$("#codolearn").hide();
});
});
Try It Yourself »
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:
$('.classSelector');
Example
$(document).ready(function(){
$("button").click(function(){
$(".codolearn").hide();
});
});
Try It Yourself »
Example of jQuery selector
Syntax |
Description |
$("*") |
Selects all elements |
|
$(this) |
Selects the current HTML element |
|
$("p.intro") |
Selects all <p> elements with class="intro" |
|
$("p:first") |
Selects the first <p> element |
|
$("ul li:first") |
Selects the first <li> element of the first <ul> |
|
$("ul li:first-child") |
Selects the first <li> element of every <ul> |
|
$("[href]") |
Selects all elements with an href attribute |
|
$("a[target='_blank']") |
Selects all <a> elements with a target attribute value equal to "_blank" |
|
$("a[target!='_blank']") |
Selects all <a> elements with a target attribute value NOT equal to "_blank" |
|
$(":button") |
Selects all <button> elements and <input> elements of type="button" |
|
$("tr:even") |
Selects all even <tr> elements |
|
$("tr:odd") |
Selects all odd <tr> elements |
|
Events in jQuery
jQuery provides simple methods for attaching event handlers to selections. When an event occurs,
the provided function is executed. Inside the function, this refers to the DOM element that
initiated the event.
jQuery Syntax For Event Methods
In jQuery, most DOM events have an equivalent jQuery method.
To assign a click event to all paragraphs on a page, you can do this:
$("p").click(function(){
// code goes your
});
Try It Yourself »
Commonly Used jQuery Event Methods
$(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully loaded.
This event is already explained in the jQuery Syntax chapter.
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:
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();
});
Try It Yourself »
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:
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:
$("p").dblclick(function(){
$(this).hide();
});
Try It Yourself »
mousedown()
The mousedown() method attaches an event handler function to an HTML element.
The function is executed, when the left, middle or right mouse button is pressed down, while the
mouse is over the HTML element:
$("#p1").mousedown(function(){
alert("HI CODOLEARNER");
});
Try It Yourself »
mouseup()
The mouseup() method adds an event handler function to an HTML element. This function is executed,
when the left mouse button is released after pressing mouse button on the HTML element. The mouseup
() event occurs when you release the pressed button of your mouse over a selected element.
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
Try It Yourself »
jQuery effects
jQuery includes methods which give special effects to the elements on hiding, showing, changing
style properties, and fade-in or fade-out operation. These special effect methods can be useful in
building an interactive user interface.
so bacically in this chapter we will learn :
- hide / show
- fade
- slide
- animate
- stop()
- callback
- chaining
Hide / show method in Query
With jQuery, you can hide and show HTML elements with the hide() and show() methods:
$("#hide").click(function(){
$("h1").hide();
});
$("#show").click(function(){
$("h1").show();
});
Try It Yourself »
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 (you will learn more about callback functions in a later chapter).
The following example demonstrates the speed parameter with hide():
$("button").click(function(){
$("p").hide(1000);
});
Try It Yourself »
Toggle() method in jQuery
$("button").click(function(){
$("p").toggle();
});
Try It Yourself »
Fading effects in jQuery
there are 4 types of fade effects
- fadein()
- fadeOut()
- fadeToggle()
- fadeTo()
jQuery fadeIn() Method
The jQuery fadeIn() method is used to fade in a hidden element.
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(1000);
});
Try It Yourself »
jQuery fadeOut() Method
The jQuery fadeOut() method is used to fade out a visible element.
$("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(1000);
});
Try It Yourself »
jQuery fadeToggle() Method
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.
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
Try It Yourself »
jQuery fadeTo() Method
The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
Try It Yourself »
Animate() method in jQuery
The animate() is an inbuilt method in jQuery which is used to change the state of the element with
CSS style. This method can also be used to change the CSS property to create the animated effect for
the selected element.
(selector).animate({styles}, para1, para2, para3);
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
Try It Yourself »
Parameter: It accepts four parameters which are specified below-
- Styles: It helps to set new css property.
- para1: It is optional parameter and used to set the speed of the parameter and
its default value is 400 millisecond.
- para2: It is optional and this specifies the speed of the element at different
position.
- para3: It is optional function that is used to be perform after animation is
complete.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
// jQuery Animate code $(document).ready(function() { $("#button").click(function() { $("#box").animate({ width: "300px" }); $("#box").animate({ height: "300px" }); }); }); </script>
<style>
div { width: 100px; height: 100px; background-color: aqua; } #button { margin-top: 10px; } </style>
</head>
<body>
<div id="box">
</div>
<!-- click on this button -->
<button id="button">
Click Here !</button>
</body>
</html>
Try It Yourself »
Sliding effects in jQuery
With jQuery you can create a sliding effect on elements.
jQuery has the following slide methods:
- slideDown()
- slideUp()
- slideToggle()
slideDown() method in jQuery
The jQuery slideDown() method is used to slide down an element.
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();
});
Try It Yourself »
jQuery slideUp() Method
The jQuery slideUp() method is used to slide up an element.
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();
});
Try It Yourself »
jQuery slideToggle() Method
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.
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 dem
onstrates the slideToggle() method:
$("#flip").click(function(){
$("#panel").slideToggle();
});
Try It Yourself »
stop() method
The stop() method is an inbuilt method in jQuery which is used to stop the currently running
animations for the selected element.
$(selector).stop(stopAll, goToEnd);
Parameters: This method accepts two parameters as mentioned above and described below:
- stopAll: It is optional parameter and the value of this parameter is boolean. This parameter is
used to specify whether or not to stop the queued animations as well. The default value of this
parameter is false.
- goToEnd: It is optional parameter and the value of this parameter is boolean. This parameter is
used to specify whether or not to complete all animations immediately. The default value of this
parameter is false.
Return Value: This method returns the selected element with stop method applied.
$(document).ready(function() {
$("#codolearn").click(function() {
$("div").animate({
height: 300
}, 1000);
$("div").animate({
width: 300
}, 1000);
});
$("#codolearn").click(function() {
$("div").stop();
});
});
Try It Yourself »
Chaining
Until now we have been writing jQuery statements one at a time (one after the other).
However, there is a technique called chaining, that allows us to run multiple jQuery commands, one
after the other, on the same element(s).
To chain an action, you simply append the action to the previous action.
The following example chains together the css(), slideUp(), and slideDown() methods. The "p1"
element first changes to red, then it slides up, and then it slides down:
We could also have added more method calls if needed.
Tip: When chaining, the line of code could become quite long. However, jQuery is not very strict on
the syntax; you can format it like you want, including line breaks and indentations.
This also works just fine:
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000);
Try It Yourself »
callback function in jQuery
JavaScript statements are always executed line by line. However, since JQuery effects require some
time to finish, the following lines of code may get executed while the previous effects are still
being executed. This is bound to create errors and overlapping of effects and animations.
To prevent this from occurring JQuery provides a callback function for each effects.
A Callback() function is executed once the effect is complete. It is always written at as the last
argument of the method.
in other words JavaScript statements are executed line by line. However, with effects, the next
line of code can be run even though the effect is not finished. ... To prevent this, you can create
a callback function. A callback function is executed after the current effect is finished.
jQuery HTML
there are some commanly used jQuery HTML are shown below :
- Get
- set
- add
- remove
- css clases
- css()
- dimensions
Get Content - text(), val() and html()
- 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
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:
$("buttons").click(function(){
alert($("#codolearn").attr("href"));
});
Try It Yourself »
Set Content - text(), html(), and val()
- 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
$("#btn1").click(function(){
$("#codolearn1").text("Hello world!");
});
$("#btn2").click(function(){
$("#codolearn2").html("Hello world!");
});
$("#btn3").click(function(){
$("#codolearn3").val("hello codolearn");
});
Try It Yourself »
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 + ")";
});
});
Try It Yourself »
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(){
$("#codolearn").attr({
"href" : "https://www.google.com",
"title" : "codolearn"
});
});
Try It Yourself »
A Callback Function for attr()
The jQuery method attr(), also comes 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(){
$("#codolearn").attr("href", function(i, origValue){
return origValue + "/jquery/";
});
});
Try It Yourself »
Add element in jQuery
- append() - Inserts content at the end of the selected elements
- prepend() - Inserts content at the beginning of the selected elements
- after() - Inserts content after the selected elements
- before() - Inserts content before the selected elements
Append method in jQuery
The . append() method inserts the specified content as the last child of each element in the jQuery
collection (To insert it as the first child, use . ... append() and . appendTo() methods perform the
same task. The major difference is in the syntax-specifically, in the placement of the content and
target.
$("p").append("CODOLEARN");
prepend method in jQuery
The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.
$("p").prepend("CODOLEARN");
How to add serveral New Elements With append() and prepend() in jQuery
In both examples above, we have only inserted some text/HTML at the beginning/end of the selected
HTML elements.
However, both the append() and prepend() methods can take an infinite number of new elements as
parameters. The new elements can be generated with text/HTML (like we have done in the examples
above), with jQuery, or with JavaScript code and DOM elements.
In the following example, we create several new elements. The elements are created with text/HTML,
jQuery, and JavaScript/DOM. Then we append the new elements to the text with the append() method
(this would have worked for prepend() too) :
jQuery after() and before() Methods
The jQuery after() method inserts content AFTER the selected HTML elements.
The jQuery before() method inserts content BEFORE the selected HTML elements.
$("img").after("CODOLEARN");
$("img").before("Some text before");
Try It Yourself »
Remove Element in jQuery
- remove() - Removes the selected element (and its child elements)
- empty() - Removes the child elements from the selected element
Remove method
The jQuery remove() method removes the selected element(s) and its child elements.
$("#codolearn").remove();
Try It Yourself »
Empty elemnet in jQuery
The empty() method is an inbuilt method in jQuery which is used to remove all child nodes and its
content for the selected elements.
$("#codolearn").empty();
Try It Yourself »
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 <p> elements with class="test":
$("h1").remove(".codolearn");
Try It Yourself »
This example removes all <p> elements with class="test" and class="demo":
$("h1").remove(".codolearn, .codolearner");
Try It Yourself »
CSS method in jQuery
The JQuery library support almost all the selector that are included in the Cascading Style Sheet
(CSS). The css() method in JQuery is used to change style property of the selected element. The
css() in JQuery can be used in different ways.
$(selector).css(property)
<!DOCTYPE html>
<html>
<head>
<title>
CODOLEARN</title>
</head>
<body>
<p style="border: 2px solid red;color:red;padding=5px;">
Welcome to CODOLEARN!.</p>
<button>
css</button>
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$("button").click(function () { $("p").css({ "backgroundColor": "red", "color": "white", "fontSize": "50px" }); });</script>
</body>
</html>
Try It Yourself »
Dimensions
jQuery provides several methods, such as height(), innerHeight(), outerHeight(), width(),
innerWidth() and outerWidth() to get and set the CSS dimensions for the elements. Check out the
following illustration to understand how these methods are calculating the dimensions of an
element's box.
width() and height() method in jQuery
The jQuery width() and height() methods get or set the width and the height of the element
respectively. This width and height doesn't include padding, border and margin on the element. The
following example will return the width and height of a
<div> element.
$(document).ready(function () {
$("button").click(function () {
var divWidth = $("#box").width();
var divHeight = $("#box").height();
$("#result").html("Width: " + divWidth + ", " + "Height: " + divHeight);
});
});
Similarly, you can set the width and height of the element by including the value as a parameter
within the width() and height() method. The value can be either a string (number and unit e.g.
100px, 20em, etc.) or a number. The following example will set the width of a <div> element to
400 pixels and height to 300 pixels respectively.
$(document).ready(function(){
$("button").click(function(){
$("#box").width(500).height(100);
});
});
Try It Yourself »
innerWidth() and innerHeight() Methods in jQuery
The jQuery innerWidth() and innerHeight() methods get or set the inner width and the inner height of
the element respectively. This inner width and height includes the padding but excludes border and
margin on the element. The following example will return the inner width and height of a <div>
element on the click of a button.
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").innerWidth();
var divHeight = $("#box").innerHeight();
$("#result").html("Inner Width: " + divWidth + ", " + "Inner Height: " + divHeight);
});
});
Similarly, you can set the element's inner width and height by passing the value as a parameter to
the innerWidth() and innerHeight() method. These methods only alter the width or height of the
element's content area to match the specified value.
For example, if the current width of the element is 300 pixels and the sum of the left and right
padding is equal to 50 pixels than the new width of the element after setting the inner width to 400
pixels is 350 pixels i.e. New Width = Inner Width - Horizontal Padding. Similarly, you can estimate
the change in height while setting the inner height.
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").outerWidth();
var divHeight = $("#box").outerHeight();
$("#result").html("Outer Width: " + divWidth + ", " + "Outer Height: " + divHeight);
});
});
Similarly, you can set the element's outer width and height by passing the value as a parameter to
the outerWidth() and outerHeight() methods. These methods only alter the width or height of the
element's content area to match the specified value, like the innerWidth() and innerHeight()
methods.
For example, if the current width of the element is 300 pixels, and the sum of the left and right
padding is equal to 50 pixels, and the sum of the width of the left and right border is 20 pixels
than the new width of the element after setting the outer width to 400 pixels is 330 pixels i.e. New
Width = Outer Width - (Horizontal Padding + Horizontal Border). Similarly, you can estimate the
change in height while setting the outer height.
$(document).ready(function(){
$("button").click(function(){
$("#box").outerWidth(400).outerHeight(300);
});
});
Jquery Ajax
Introduction
The following tutorial will provide a short introduction to Ajax and its uses. Before
understanding these terms see few practical examples to demonstrate the power of Ajax. Facebook,
Instagram, Twitter etc are considered the situation when check news feed and if like someone post
simply click the like button and the like count is added without refreshing the page. Now imagine
the situation if there would be the case, click the like button and the complete page would be
loaded again which will make such processes. Now the question whether clicking the button again for
such a small task which require complete loading of a web page. Absolutely not, because no one will
do such an absurd thing (in the latter case). So it means that this feature of like is very helpful
as it prevents the reloading of the complete page. It communicates only necessary information with
the server and shows to the end user(in this case being the increase of like count).
Consider another case when visit google to search for anything. Usually, observe that when start
typing the desired keywords to search, observe that many suggestions are presented in the search
bar. Now, where do they come from? Of course not from the client side. The results are again the
power of communication with the server without reloading the page again.
Like this, there are dozens of examples which can be considered. The whole power working behind is
nothing but Ajax. Let’s discuss briefly Ajax and its implementation.
what do you mean by ajax ?
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster,
and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
-
Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and
JavaScript for dynamic content display.
-
Conventional web applications transmit information to and from the sever using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new
information from the server.
-
With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the
results, and update the current screen. In the purest sense, the user would never know that
anything was even transmitted to the server.
-
XML is commonly used as the format for receiving server data, although any format, including
plain text, can be used.
-
AJAX is a web browser technology independent of web server software.
-
A user can continue to use the application while the client program requests information from
the server in the background.
-
Intuitive and natural user interaction. Clicking is not required, mouse movement is a
sufficient event trigger.
-
Data-driven as opposed to page-driven.
What About jQuery and AJAX?
jQuery provides several methods for AJAX functionality.
With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using
both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML
elements of your web page!
How it works ?
First, let us understand what does asynchronous actually mean. There are two types of requests
synchronous as well as asynchronous. Synchronous requests are the one which follows sequentially i.e
if one process is going on and in the same time another process wants to be executed, it will not be
allowed that means the only one process at a time will be executed. This is not good because in this
type most of the time CPU remains idle such as during I/O operation in the process which are the
order of magnitude slower than the CPU processing the instructions. Thus to make the full
utilization of the CPU and other resources use asynchronous calls. For more information visit this
link. Why the word javascript is present here. Actually, the requests are made through the use of
javascript functions. Now the term XML which is used to create XMLHttpRequest object.
Thus the summary of the above explanation is that Ajax allows web pages to be updated asynchronously
by exchanging small amounts of data with the server behind the scenes. Now discuss the important
part and its implementation. For implementing Ajax, only be aware of XMLHttpRequest object. Now,
what actually it is. It is an object used to exchange data with the server behind the scenes. Try to
remember the paradigm of OOP which says that object communicates through calling methods (or in
general sense message passing). The same case applied here as well. Usually, create this object and
use it to call the methods which result in effective communication. All modern browsers support the
XMLHttpRequest object.
load() method in jQuery
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. Syntax: ... The optional callback
parameter is the name of a function to be executed after the load() method is completed.
$(selector).load(URL,data,callback);
Try It Yourself »
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.
Here is the content of our example file: "codolearn.txt":
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 succeeds
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 succeeded, 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("content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
Try It Yourself »
HTTP Request: GET vs. POST
Two commonly used methods for a request-response between a client and server are: GET and POST.
- GET - Requests data from a specified resource
- POST - Submits data to be processed to a specified resource
Get method in jQuery
In jQuery . get() method loads data from the server by using the GET HTTP request. This method
returns XMLHttpRequest object. data : This is an optional parameter that represents key/value pairs
that will be sent to the server.
$("button").click(function(){
$.get("Codolearnasp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
Try It Yourself »
POST method in jQuery
jQuery post() Method. The jQuery post() method sends asynchronous http POST request to the server to
submit the data to the server and get the response. ... data: json data to be sent to the server
with request as a form data. callback: function to be executed when request succeeds. type: data
type of the response content.
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.txt",
{
name: "CODOLEARN",
city: "new york"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
The first parameter of $.post() is the URL we wish to request ("demo.txt").
Then we pass in some data to send along with the request (name and city).
The ASP script in "demo.txt" reads the parameters, processes them, and returns 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.