Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
136 views

J Query

jQuery selectors enable you to find DOM elements in a webpage. Common selectors include selecting elements by name, id, class, attribute, or input type. jQuery selectors use CSS selector patterns and allow selecting elements in different ways, such as by descendant, child, or attribute relationships.

Uploaded by

Argha Sen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
136 views

J Query

jQuery selectors enable you to find DOM elements in a webpage. Common selectors include selecting elements by name, id, class, attribute, or input type. jQuery selectors use CSS selector patterns and allow selecting elements in different ways, such as by descendant, child, or attribute relationships.

Uploaded by

Argha Sen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

jQuery Selectors

In this section, you will learn about jQuery selectors and how to find
DOM element(s) using selectors.

The jQuery selector enables you to find DOM elements in your web
page. Most of the times you will start with selector function $() in the
jQuery.

Syntax:
$(selector expression, context)

jQuery(selector expression, context)

The selector expression parameter specifies a pattern to match the


elements. The jQuery uses CSS selector patterns as well as its own
pattern to match the elements.

The context parameter is optional. It specifies elements in a DOM


hierarchy from where jQuery starts searching for matching elements.

Let's see commonly used selectors in jQuery.

Select Elements by Name


The most common selector pattern is element name. Specifing an
element name as string e.g. $('p') will return an array of all the <p>
elements in a webpage.

The following figure shows which DOM elements will be returned from
$('p') & $'(div').
jQuery Selectors Demo

As you can see in the above figure, $('div') will return all the <div>
elements including its child elements.

Example: Select Elements by Name


$('p').append('This is paragraph.'); // appends text to all p
elements $('div').append('This is div.); // appends text to all
div elements <div> <p></p> <p></p> </div> <p></p> <div></div>
Try it

Select Elements by Id

jQuery append() method inserts text at the end in the element.

You can get a particular element by using id selector pattern. Specify


an id of an element for which you want to get the reference, starting
with # symbol.

The following figure shows which DOM elements will be returned from
$('#myDiv1') & $'(#prg2').
jQuery Id
Selector Demo
Example: Select Element by #Id
$('#impPrg').append('This element\'s id is "impPrg"');
$('#myDiv2').append('This element\'s id is "myDiv2"'); <div
id="myDiv1"> <p></p> </div> <p id="impPrg"></p> <div
id="myDiv2"> </div>
Try it

Select Elements by Attribute


jQuery also allows you to find an element based on attributes set on it.
Specifing an attribute name in square brackets in $ function e.g.
$('[class]') will return all the elements that have class attribute
irrespective of value.

In the following example, jQuery returns all the elements that have
class or contenteditable attribute irrespective of any value.
jQuery Attribute Selector
Example: Select Elements by Attribute
$('[class]').append('This element has class attribute'); <div
id="myDiv1"> <p></p> </div> <p id="impPrg" class="boldPrg"></p>
<div id="myDiv2" class="yellowDiv"> </div>
Try it

You can also specify a specific value of an attribute in attribute


selector. For example, $('[class="myCls"]') will return all the elements
which have class attribute with myCls as a value.

jQuery Selector by Attribute Value


Example: Select Element by Attribute Value
$('[class="yellowDiv"]').append('This element includes
class="yellowDiv" attribute'); <div id="myDiv1"> <p></p> </div>
<p id="impPrg" class="boldPrg">This is paragraph.</p> <div
id="myDiv2" class="yellowDiv"> </div>
Try it

jQuery Selector Patterns


jQuery provides number of ways to select a specific DOM element(s).
The following table lists the most important selector patterns.

Category Selector Description

Find element $('div') Find all <div> elements

$('p, div, code') Find <p>,<div> and <code>


elements

Find $('div p') Find all <p> elements which are


descendant descendants of <div>
elements

$('div > p') Find <p> which is child of <div>

$(*) Find all elements

Find by Id $('#myDiv') Find element whose id is myDiv

$('div#myDiv') Find <div> element whose Id is


myDiv

$('#myDiv1, #myDiv2') Find multiple elements by id


separated by comma.
Find by CSS $('.myCSSClass') Find all the elements with
class class=myCSSClass.

$('.myCSSClass1, .myCSSClass2 Finds all elements whose class


') attribute is set to myCSSClass1
or myCSSClass2

$('div.myCSSClass') Finds all <div> elements with


class=myCSSClass

Find child $('p:first-child') Find all <p> elements, which is


element the first child of its parent
element. (parent element can
be anything)

$("p:last-child") Selects all <p> elements which


is the last child of its parent
element. (parent element can
be anything)

$("p:nth-child(5)") Selects all <p> elements which


is the 5th child of its parent
element. (parent element can
be anything)

$("p:nth-last-child(2)") Selects all <p> elements which


is the 2nd last child of its parent
element. (parent element can
be anything)

$("p:only-child") Selects all <p> elements which


is the only child of its parent
element. (parent element can
be anything)

Find by $('[class]') Find all the elements with the


attribute class attribute(whatever the
value).
$('div[class]') Find all the <div> elements that
have a class attribute(whatever
the value).

Find by $('div[class=myCls]') Find all the <div> elements


containing whose class attributes are equal
value of to myCls.
attribute

$('div[class|=myCls]') Find all the <div> elements


whose class attributes are either
equal to myCls or starting with
myCls string followed by a
hyphen (-).

$('div[class *="myCls"]') Selects <div> elements whose


class attributes contain myCls.

$('div[class~=myCls]') Selects div elements whose


class attributes contain myCls,
delimited by spaces.

$("div[class $= 'myCls']") Selects <div> elements whose


class attribute value ends with
myCls. The comparison is case
sensitive.

$("div[class != 'myCls']") Selects <div> elements which


do not have class attribute or
value does not equal to myCls.

$("div[class ^= 'myCls']") Selects <div> elements whose


class attribute value starts with
myCls.

$("div:contains('tutorialsteacher' Selects all <div> elements that


)" contains the text
'tutorialsteacher'

Find by $(":input") Selects all input elements.


input type
:button $(":button") Selects all input elements where
type="button".

:radio $(":radio") Selects all input types where


type="radio"

:text $(":text") Selects all input elements where


type="text" .

":checkbox" $(":checkbox") Selects all checkbox elements.

:submit $(":submit") Selects all input elements where


type="submit".

:password $(":password") Selects all input elements where


type="password".

:reset $(":reset") Selects all input elements where


type="reset".

:image $(':image') Selects all input elements where


type="image".

:file $(':file') Selects all input elements where


type="file".

:enabled $(':enabled') Selects all enabled input


elements.

:disabled $(':disabled') Selects all disabled input


elements.

:selected $(':selected') Selects all selected input


elements.

:checked $(':checked') Selects all checked input


elements.
:hidden $(':hidden') Selects all hidden elements.

:visible $(':visible') Selects all visible elements.

:odd $('tr:odd') Selects all odd rows. (1,3,5,7..)

:even $('tr:even') Selects all even rows.(0,2,4,6..)

DOM Manipulation Methods in


jQuery
jQuery provides various methods to add, edit or delete DOM
element(s) in the HTML page.

The following table lists some important methods to add/remove new


DOM elements.

Method Description

append() Inserts content to the end of element(s) which is specified by a


selector.

before() Inserts content (new or existing DOM elements) before an


element(s) which is specified by a selector.

after() Inserts content (new or existing DOM elements) after an element(s)


which is specified by a selector.

prepend() Insert content at the beginning of an element(s) specified by a


selector.
remove() Removes element(s) from DOM which is specified by selector.

replaceAll() Replace target element(s) with specified element.

wrap() Wrap an HTML structure around each element which is specified by


selector.

The following figure shows how the DOM manipulation methods add
new elements.

DOM Manipulation Methods

Let's have a quick overview of important DOM manipulation methods.

jQuery after() Method


The jQuery after() method inserts content (new or existing DOM
elements) after target element(s) which is specified by a selector.

Syntax:
$('selector expression').after('content');

First of all, specify a selector to get the reference of target element(s)


after which you want to add the content and then call after() method.
Pass the content string as a parameter. Content string can be any valid
HTML element.

Example: jQuery after() Method


$('#div1').after('<div style="background-color:yellow"> New div
</div>'); <div id="div1">div 1 </div> <div id="div2">div 2
</div>
Try it
Result:
<div id="div1">div 1 </div> <div
style="background-color:yellow"> New div </div> <div
id="div2">div 2 </div>

jQuery before() Method


The jQuery before() method inserts content (new or existing DOM
elements) before target element(s) which is specified by a selector.

Syntax:
$('selector expression').before('content');

Specify a selector to get the reference of target element(s) before


which you want to add the content and then call before() method. Pass
the content string that can be any valid HTML element as parameter.

Example: jQuery before() Method


$('#div1').before('<div style="background-color:yellow"> New div
</div>'); <div id="div1">div 1 </div> <div id="div2">div 2
</div>
Try it
Result:
<div style="background-color:yellow"> New div </div> <div
id="div1">div 1 </div> <div id="div2">div 2 </div>

jQuery append() Method


The jQuery append() method inserts content to the end of target
element(s) which is specified by a selector.

Syntax:
$('selector expression').append('content');

First specify a selector expression to get the reference of an


element(s) to which you want to append content, then call append()
method and pass content string as a parameter.

Example: jQuery append() Method


$('p').append('World!'); <p>Hello </p>
Try it
Result:
<p>Hello World!</p>

jQuery prepend() Method


The jQuery prepend() method inserts content at the beginning of an
element(s) specified by a selector.

Syntax:
$('selector expression').prepend('content');

First specify a selector expression to get the reference of an


element(s) to which you want to prepend the content, then call
prepend() method and pass content string as a parameter.

Example: jQuery prepend() Method


$('div').prepend('<p>This is prepended paragraph</p>'); <div>
<label>This is div.</label> </div>
Try it
Result:
<div> <p>This is prepended paragraph</p> <label>This is
div.</label> </div>
jQuery remove() Method
The jQuery remove() method removes element(s) as specified by a
selector.

Syntax:
$('selector expression').remove();

First specify a selector expression to get the reference of an


element(s) which you want to remove from the document and then
call remove() method.

Example: jQuery remove() Method


$('label').remove(); <div>This is div. <label>This is
label.</label> </div>
Try it
Result:
<div> This is div. </div>

jQuery replaceAll() Method


The jQuery replaceAll() method replaces all target elements with
specified element(s).

Syntax:
$('content string').replaceAll('selector expression');

Here, syntax is different. First specify a content string as replacement


element(s) and then call replaceAll() method with selector expression
to specify a target element(s).

Example: jQuery replaceAll() Method


$('<span>This is span</span>').replaceAll('p'); <div> <p>This is
paragraph.</p> </div> <p>This is another paragraph.</p>
Try it
Result:
<div> <span>This is span</span> </div> <span>This is span</span>

jQuery wrap() Method


The jQuery wrap() method wrap each target element with specified
content element.

Syntax:
$('selector expression').wrap('content string');

Specify a selector to get target elements and then call wrap method
and pass content string to wrap the target element(s).

Example: jQuery wrap() Method


$('span').wrap('<p></p>'); <div> <span>This is span.</span>
</div> <span>This is span.</span>
Try it
Result:
<div> <p> <span>This is span.</span></p> </div> <p><span>This is
span.</span></p>

Manipulate DOM Element's


Dimensions using jQuery
The jQuery library includes various methods to manipulate DOM
element's dimensions like height, width, offset, position etc.

The following table lists all the jQuery methods to get or set DOM
element's dimensions.
jQuery Method Description

height() Get or set height of the specified element(s).

innerHeight() Get or set inner height (padding + element's height) of the


specified element(s).

outerHeight() Get or set outer height (border + padding + element's height) of


the specified element(s).

offset() Get or set left and top coordinates of the specified element(s).

position() Get the current coordinates of the specified element(s).

width() Get or set the width of the specified element(s).

innerWidth() Get or set the inner width (padding + element's width) of the
specified element(s).

outerWidth() Get or set outer width (border + padding + element's width) of


the specified element(s).

The following figure shows various dimensions of an element.


DOM Element's Dimensions

jQuery height() Method


The jQuery height()method gets or sets height of the specified DOM
element(s).

Syntax:
$('selector expression').height(value);

Specify a selector to get the reference of an element and call height()


method to get the height in pixel. To set the height of specified
elements, specify height as integer parameter in height() method.

Example: jQuery height() Method


$('#myDiv').height(); //returns height of #myDiv in pixels
$('p').height(); //returns height in pixel //set height of all
div elements $('div').height(100); <div id="myDiv" > This is
div. </div> <p> This is paragraph. </p>
Try it

jQuery width() Method


The jQuery width() method gets or sets width of the specified DOM
element(s).

Syntax:
$('selector expression').width(value);

Specify a selector to get the reference of an element and call width()


method to get the width in pixel. Specify width as integer parameter to
set the width.

Example: jQuery width() Method


$('#myDiv').width(); //returns width of #myDiv in pixels
$('p').width(); //returns width of p in pixel //set width of all
div elements $('div').width(100); <div id="myDiv" > This is div.
</div> <p> This is paragraph. </p>
Try it

jQuery offset() Method


The jQuery offset() method gets or sets coordinates of the specified
element(s).

Syntax:
$('selector expression').offset(options);

Specify a selector to get the reference of an element and call offset()


method to get the jQuery object which has left and top property.
Specify JSON object with left and top property with the coordinates
where you want to move the element.

Example: jQuery offset() Method


var ofs = $('#myDiv').offset(); alert('left:' + ofs.left + ',
top: ' + ofs.top); $('p').offset({ left:100, top:200}); <div
id="myDiv" > This is div. </div> <p> This is paragraph. </p>
Try it

Visit DOM manipulation methods reference to know all the methods to


manipulate dimensions.

Points to Remember :
​ jQuery dimension methods allows you to manipulate dimensions
of DOM elements.
​ Use the selector to get the reference of an element(s) and then
call jQuery dimension methods to edit it.
​ Important DOM manipulation methods: height(), width(),
offset(), position() etc.

jQuery Events
You will learn about jQuery events in this section.

In most web applications, the user does some action to perform an


operation. For example, user clicks on save button to save the edited
data in a web page. Here, clicking on the button is a user's action,
which triggers click event and click event handler (function) saves
data.
Event

jQuery Event Methods


The jQuery library provides methods to handle DOM events. Most
jQuery methods correspond to native DOM events.

The following table lists all jQuery methods and corresponding DOM
events.

Category jQuery Method DOM Event

Form events blur onblur

change onchange

focus onfocus

focusin onfocusin

select onselect

submit onsubmit

Keyboard events keydown onkeydown

keypress onkeypress
keyup onkeyup

focusout

Mouse events click onclick

dblclick ondblclick

focusout

hover

mousedown onmousedown

mouseenter onmouseenter

mouseleave onmouseleave

mousemove onmousemove

mouseout onmouseout

mouseover onmouseover

mouseup onmouseup

Toggle

Browser events Error onerror()

Resize onresize

Scroll onscroll

Document loading Load onload


Ready

Unload onunload

Event Handling
To handle DOM events using jQuery methods, first get the reference of
DOM element(s) using jQuery selector and invoke appropriate jQuery
event method.

The following example shows how to handle button click event.

Example:Handle Button Click Event


$('#saveBtn').click(function () { alert('Save button clicked');
}); <input type="button" value="Save" id="saveBtn" />
Try it

In the above example, we first use id selector to get a reference of


'Save' button and then call click method. We have specified handler
function as a callback function, which will be called whenever click
event of Save button is triggered.

Event Object

jQuery passes an event object to every event handler function. The


event object includes important properties and methods for
cross-browser consistency e.g. target, pageX, pageY, relatedTarget etc.

Example: jQuery Event Object


$('#saveBtn').click(function (eventObj) { alert('X =' +
eventObj.pageX + ', Y =' + eventObj.pageY); }); <input
type="button" value="Save" id="saveBtn" />
Try it
this Keyword in Event Handler

this keyword in an event handler represents a DOM element which


raised an event.

Example: this in Event Handler


$(':button').click(function (eventObj) { alert(this.value + ' '
+ this.type + ' clicked'); }); <input type="button" value="Save"
id="saveBtn" /> <input type="button" value="Delete" id="delBtn"
/> <input type="button" value="Clear" id="clearBtn" />
Try it

Hover Events

jQuery provides various methods for mouse hover events e.g.


mouseenter, mouseleave, mousemove, mouseover, mouseout and
mouseup.

Example: Hover Events


$('#myDiv').mouseenter(function (data) {
$(this).css('background-color','green'); });
$('#myDiv').mouseleave(function (data) {
$(this).css('background-color','red'); }); <div id="myDiv"
style="width:100px;height:100px"> </div>
Try it

You can use hover() method instead of handling mouseenter and


mouseleave events separately.

Example: hover() Method


$('#myDiv').hover(function () {
$(this).css('background-color','green'); }, function () {
$(this).css('background-color','red'); }); <div id="myDiv"
style="width:100px;height:100px"> </div>
Try it
Event Binding using on()
jQuery allows you to attach an event handler for one or more events
to the selected elements using on method.

Internally all of the shorthand methods uses on() method. The on()
method gives you more flexibility in event binding.

Syntax:
on(types, selector, data, fn )
● Types = One or more space-separated event types and optional
namespaces
● Selector = selector string
● Data = data to be passed to the handler in event.data when an event
is triggered.
● Fn = A function to execute when the event is triggered.

Example: Event Binding using on


$('#saveBtn').on('click',function () { alert('Save Button
clicked'); }); <input type="button" value="Save" id="saveBtn" />
Try it

You can use selector to filter the descendants of the selected elements
that trigger the event.

Example: Event Binding using on


$('#myDiv').on('click',':button', function () { alert('Button
clicked'); }); <div id="myDiv" > <input type="button"
value="Save" id="saveBtn" /> <input type="button" value="Add"
id="addBtn" /> </div> <input type="button" value="Delete"
id="delBtn" />
Try it

In the above example, we specify ':button' selector. So click event


triggered by buttons in <div> tag whose id is myDiv, will only be
handled.
Binding Multiple Events
You can also specify multiple event types separated by space.

Example: Multiple Events Binding


$( 'myDiv' ).on('mouseenter mouseleave', function() {
$(this).text('The mouse entered or left from the div' ); });
<div id="myDiv" style="width:100px;height:100px"> </div>

Try it

Specify Named Function as Event Handler

You can create separate functions and specify that as a handler. This is
useful if you want to use the same handler for different events or
events on different elements.

Example:Binding Named Function to Event


var mouseHandler = function() { alert( "The mouse entered" ); };
$('#myDiv').on('mouseenter', mouseHandler); <div id="myDiv"
style="width:100px;height:100px"> </div>

Try it

jQuery on() method is replacement of live() and delegate() method.

Event Bubbling
The following example demonstrates event bubbling in jQuery.

Example:Event Bubbling
$('div').click(function (event) { alert( event.target.tagName +
' clicked'); }); <div> <p> <span>This is span.</span> </p>
</div>
Try it
As you can see in the above example, we have handled click event of
<div> element in jQuery. So if you click on div, it will display alert
message 'DIV clicked'. However, if you click on span, still it will popup
alert message SPAN clicked even though we have not handled click
event of <span>. This is called event bubbling. Event bubbles up to
the document level in DOM hierarchy till it finds it.

The following figure illustrates event bubbling.

jQuery Event Bubbling

Visit event methods reference to know about all the event methods in
jQuery.

Points to Remember :
​ The jQuery event methods allow you to attach event handler or
fire native DOM events.
​ Use the selector to get the reference of an element(s) and then
call jQuery event methods to fire it or attach an event handler.
​ Important DOM manipulation methods: click(), dblClick(),
change(), submit(), keyup(), keydown(), mouseenter(),
mouseleave(), hover() etc.

jQuery ajax() Method


The jQuery ajax() method provides core functionality of Ajax in jQuery.
It sends asynchronous HTTP requests to the server.

Syntax:
$.ajax(url);

$.ajax(url,[options]);

Parameter description:

● url: A string URL to which you want to submit or retrieve the data
● options: Configuration options for Ajax request. An options
parameter can be specified using JSON format. This parameter is
optional.

The following table list all the options available for configuring Ajax
request.

Options Description

accepts The content type sent in the request header that tells the server
what kind of response it will accept in return.

async By default, all requests are sent asynchronously. Set it false to


make it synchronous.

beforeSend A callback function to be executed before Ajax request is sent.


cache A boolean indicating browser cache. Default is true.

complete A callback function to be executed when request finishes.

contentType A string containing a type of content when sending MIME content


to the server.Default is "application/x-www-form-urlencoded;
charset=UTF-8"

crossDomain A boolean value indicating whether a request is a cross-domain.

data A data to be sent to the server. It can be JSON object, string or


array.

dataType The type of data that you're expecting back from the server.

error A callback function to be executed when the request fails.

global A Boolean indicating whether to trigger a global Ajax request


handler or not. Default is true.

headers An object of additional header key/value pairs to send along with


request.

ifModified Allow the request to be successful only if the response has


changed since the last request. This is done by checking the
Last-Modified header. Default value is false.

isLocal Allow the current environment to be recognized as local.

jsonp Override the callback function name in a JSONP request. This


value will be used instead of 'callback' in the 'callback=?' part of
the query string in the url.

jsonpCallback String containing the callback function name for a JSONP request.

mimeType String containing a mime type to override the XMLHttpRequest


mime type.
password A password to be used with XMLHttpRequest in response to an
HTTP access authentication request.

processData A Boolean indicating whether data assigned to data option will be


converted to a query string. Default is true.

statusCode A JSON object containing numeric HTTP codes and functions to be


called when the response has the corresponding code.

success A callback function to be executed when Ajax request succeeds.

timeout A number value in milliseconds for the request timeout.

type A type of http request e.g. POST, PUT and GET. Default is GET.

url A string containing the URL to which the request is sent.

username A username to be used with XMLHttpRequest in response to an


HTTP access authentication request.

xhr A callback for creating the XMLHttpRequest object.

xhrFields An object of fieldName-fieldValue pairs to set on the native


XMLHttpRequest object.

Let's see how to send http requests using $.ajax() (or jQuery.ajax())
method.

Send Ajax Request


The ajax() methods performs asynchronous http request and gets the
data from the server. The following example shows how to send a
simple Ajax request.

Example: jQuery Ajax Request


$.ajax('/jquery/getdata', // request url { success: function
(data, status, xhr) {// success callback function
$('p').append(data); } }); <p></p>
Try it

In the above example, first parameter '/getData' of ajax() method is a


url from which we want to retrieve the data.

By default ajax() method performs http GET request if option


parameter does not include method option.

The second parameter is options parameter in JSON format where we


have specified callback function that will be executed when request
succeeds. You can configure other options as mentioned in the above
table.

The following example shows how to get the JSON data using ajax()
method.

Example: Get JSON Data


$.ajax('/jquery/getjsondata', { dataType: 'json', // type of
response data timeout: 500, // timeout milliseconds success:
function (data,status,xhr) { // success callback function
$('p').append(data.firstName + ' ' + data.middleName + ' ' +
data.lastName); }, error: function (jqXhr, textStatus,
errorMessage) { // error callback $('p').append('Error: ' +
errorMessage); } }); <p></p>
Try it

In the above example, first parameter is a request url which will return
JSON data. In the options parameter, we have specified dataType and
timeout options. The dataType option specifies the type of response
data, in this case it is JSON. The timeout parameter specifies request
timeout in milliseconds. We have also specified callback functions for
error and success.
The ajax() method returns an object of jQuery XMLHttpRequest. The
following example shows how to use jQuery XMLHttpRequest object.

Example: ajax() Method


var ajaxReq = $.ajax('GetJsonData', { dataType: 'json', timeout:
500 }); ajaxReq.success(function (data, status, jqXhr) {
$('p').append(data.firstName + ' ' + data.middleName + ' ' +
data.lastName); }) ajaxReq.error(function (jqXhr, textStatus,
errorMessage) { $('p').append('Error: ' + errorMessage); })
<p></p>
Try it

Send Http POST request using ajax()


The ajax() method can send all type of http requests. The following
example sends http POST request to the server.

Example: Send POST Request


$.ajax('/jquery/submitData', { type: 'POST', // http method
data: { myData: 'This is my data.' }, // data to submit success:
function (data, status, xhr) { $('p').append('status: ' + status
+ ', data: ' + data); }, error: function (jqXhr, textStatus,
errorMessage) { $('p').append('Error' + errorMessage); } });
<p></p>
Try it

In the above example, first parameter is a url which is used to submit


the data. In the options parameter, we have specified a type option as
a POST, so ajax() method will send http POST request. Also, we have
specified data option as a JSON object containing data which will be
submitted to the server.

So this way you can send GET, POST or PUT request using ajax()
method.

Visit jQuery documentation to know more about ajax() method.


Points to Remember :
​ $.ajax() method allows you to send asynchronous http requests
to submit or retrieve data from the server without reloading the
whole page.
​ $.ajax() can be used to send http GET, POST, PUT, DELETE etc.
request. It can retrieve any type of response from the server.
​ Syntax: $.ajax(url,[options])
​ Use option parameter to customize ajax request as per your
need.

jQuery get() Method


The jQuery get() method sends asynchronous http GET request to the
server and retrieves the data.

Syntax:
$.get(url, [data],[callback]);

Parameters Description:

● url: request url from which you want to retrieve the data
● data: data to be sent to the server with the request as a query
string
● callback: function to be executed when request succeeds

The following example shows how to retrieve data from a text file.

Example: jQuery get() Method


$.get('/data.txt', // url function (data, textStatus, jqXHR) {
// success callback alert('status: ' + textStatus + ', data:' +
data); });

In the above example, first parameter is a url from which we want to


retrieve the data. Here, we want to retrieve data from a txt file located
at mydomain.com/data.txt. Please note that you don't need to give
base address.

Internally, jQuery get() method calls ajax() method only. Visit


james.padolsey.com/jquery and search for get() method to see the source code.

The second parameter is a callback function that will be executed when


this GET request succeeds. This callback function includes three
parameters data, textStatus and jQuery wrapper of XMLHttpRequest
object. Data contains response data, textStatus contains status of
request and jqXHR is a jQuery XMLHttpRequest object which you can
use for further process.

The following example shows how to retrieve JSON data using get()
method.

Example: Retrieve JSON Data using get()


$.get('/jquery/getjsondata', {name:'Steve'}, function (data,
textStatus, jqXHR) { $('p').append(data.firstName); }); <p></p>
Try it

In the above example, first parameter is a url from which we want to


retrieve JSON data. This url can be a web service or any other url that
returns data in JSON format.

The second parameter is data to be sent to the server as a query


string. We have specified name parameter with value 'Steve' in the
JSON format. So now, the request url would look like
http://mydomain.com/jquery/getjsondata?name=Steve

The third parameter is a callback function that will be executed when


this GET request succeeds.
jQuery getJSON() Method
The jQuery getJSON() method sends asynchronous http GET request
to the server and retrieves the data in JSON format by setting accepts
header to application/json, text/javascript. This is same as get()
method, the only difference is that getJSON() method specifically
retrieves JSON data whereas get() method retrieves any type of data.
It is like shortcut method to retrieve JSON data.

Syntax:
$.getJSON(url,[data],[callback]);

Parameter Description:

● url: request url from which you want to retrieve the data
● data: JSON data to be sent to the server as a query string
● callback: function to be executed when request succeeds

The following example shows how to retrieve JSON data using


getJSON() method.

Example: jQuery getJSON() Method


$.getJSON('/jquery/getjsondata', {name:'Steve'}, function (data,
textStatus, jqXHR){ $('p').append(data.firstName); }); <p></p>
Try it

In the above example, first parameter is a url from which we want to


get JSON data. This can be a web service or any other url that returns
JSON data.

The second parameter is data to pass as query string with the GET
request. So now, the request url would look like
http://mydomain.com/jquery/getjsondata?name=Steve
Internally, jQuery getJSON() method calls get() method and set
dataType to JSON. Visit james.padolsey.com/jquery and search for get()
method to see the source code.

The third parameter is a callback function which will be executed when


request succeeds. The data parameter will be in the JSON format
because getJson() method automatically converts server response into
a JSON object.

You can attach fail and done callback methods to getJson() method as
shown below.

Example: getJSON() Method


$.getJSON('/jquery/getjsondata', { name:'Steve'}, function(data,
textStatus, jqXHR){ alert(data.firstName); }) .done(function ()
{ alert('Request done!'); }) .fail(function (jqxhr,settings,ex)
{ alert('failed, '+ ex); });
Try it

jQuery getScript() Method


The jQuery getScript() method sends http GET request to the server,
retrieves the JavaScript file and then executes it. Internally, jQuery
getScript() method calls get() method and sets dataType to script.

Syntax:
$.getScript(url, [callback]);

Parameter Description:

● url: request url from which you want to download JavaScript file
● callback: function to be executed when request succeeds
The following example shows how to download script file using
getScript() method.

Example: jQuery getScript() Method


$.getScript('/Scripts/myJavaScriptFile.js',
function(script,status,jqxhr){ alert(status); });

In the above example, first parameter is a url from which we want to


download script file. Here, we download myJavaScriptFile.js file for
demo purpose.

The second parameter is a callback function which will be executed


when request succeeds.

Thus, you can use different get methods to retrieve different types of
resources using http get request.

Points to Remember :
​ $.get(), $.getJSON() method allows you to send asynchronous
http GET request to retrieve the data from the server without
reloading whole page.
​ $.get() can be used to retrieve any type of response from the
server.
​ $.getJSON() method is a short form method to retrieve JSON
response from the server.
​ $.getScript() sends asynchronous http GET request to retrieve
the script files from the server and execute it.
​ Syntax:
$.get(url,[data],[callback])
$.getJSON(url,[data],[callback])
$.getScript(url,[callback])

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.

Syntax:
$.post(url,[data],[callback],[type]);

Parameter Description:

● url: request url from which you want to submit & retrieve the
data.
● 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.

Let's see how to submit data and get the response using post()
method. Consider the following example.

Example: jQuery post() Method


$.post('/jquery/submitData', // url { myData: 'This is my data.'
}, // data to be submit function(data, status, jqXHR) {//
success callback $('p').append('status: ' + status + ', data: '
+ data); }) <p></p>
Try it

In the above example, first parameter is a url to which we want to


send http POST request and submit the data.

Internally, post() method calls ajax() method with method option to


POST. Visit james.padolsey.com/jquery and search for post() method to see the
jQuery source code.

The second parameter is a data to submit in JSON format, where key


is the name of a parameter and value is the value of parameter.
The third parameter is a success callback function that will be called
when request succeeds. The callback function can have three
parameters; data, status and jqXHR. The data parameter is a response
coming from the server.

The following example shows how to submit and retrieve JSON data
using post() method.

Example: submit JSON Data using post() Method


$.post('/submitJSONData', // url { myData: 'This is my data.' },
// data to be submit function(data, status, xhr) { // success
callback function alert('status: ' + status + ', data: ' +
data.responseData); }, 'json'); // response data format

In the above example, please notice that last parameter is a type of


response data. We will get JSON data as a server response. So post()
method will automatically parse response into JSON object. Rest of the
parameters are same as first example.

You can also attach fail and done callback methods to post() method
as shown below.

Example: jQuery post() Method


$.post('/jquery/submitData', { myData: 'This is my data.' },
function(data, status, xhr) { $('p').append('status: ' + status
+ ', data: ' + data); }).done(function() { alert('Request
done!'); }) .fail(function(jqxhr, settings, ex) { alert('failed,
' + ex); }); <p></p>
Try it

Points to Remember :
​ $.post() method allows you to send asynchronous http POST
request to submit and retrieve the data from the server without
reloading whole page.
​ Syntax:
$.post(url,[data],[callback],[type])
​ Specify type parameter for the type of response data e.g.
specify 'JSON' if server return JSON data.
​ Internally post() method calls ajax() method only by passing
method='POST' as option.

jQuery load() Method


The jQuery load() method allows HTML or text content to be loaded
from a server and added into a DOM element.

Syntax:
$.load(url,[data],[callback]);

Parameters Description:

● url: request url from which you want to retrieve the content
● data: JSON data to be sent with request to the server.
● callback: function to be executed when request succeeds

The following example shows how to load html content from the server
and add it to div element.

Example: Load HTML Content


$('#msgDiv').load('/demo.html'); <div id="msgDiv"></div>

In the above example, we have specified html file to load from the
server and add its content to the div element.

Note : If no element is matched by the selector then Ajax request will not be
sent.

The load() method allows us to specify a portion of the response


document to be inserted into DOM element. This can be achieved using
url parameter, by specifying selector with url separated by one or
multiple space characters as shown in the following example.

Example: jQuery load() Method


$('#msgDiv').load('/demo.html #myHtmlContent'); <div
id="msgDiv"></div>

In the above example, content of the element whose id is


myHtmlContent, will be added into msgDiv element. The following is a
demo.html.

demo.html content:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
<head> <title></title> </head> <body> <h1>This is demo html
page.</h1> <div id="myHtmlContent">This is my html
content.</div> </body> </html>

The load() method also allows us to specify data to be sent to the


server and fetch the data.

Example: Set Data in load()


$('#msgDiv').load('getData', // url { name: 'bill' }, // data
function(data, status, jqXGR) { // callback function alert('data
loaded') }); <div id="msgDiv"></div>
Try it

In the above example, first parameter is a url from which we want to


fetch the resources. The second parameter is data to be sent to the
server. The third parameter is a callback function to execute when
request succeeds.

Points to Remember :
​ $.load() method allows HTML or text content to be loaded from
a server and added into a DOM element.
​ Syntax:
$.post(url,[data],[callback])
​ Specify selector with url to specify a portion of the response
document to be inserted into DOM element.
$('#msgDiv').load('/demo.html #myHtmlContent');

You might also like