jQuery and AJAX
jQuery provides several methods for AJAX functionality.
By using jQuery AJAX methods, we can get text, HTML, XML, or JSON from the server using either HTTP Get or HTTP Post . We can load the external data directly into the selected HTML elements of your web page.
Now let’s see how we can load the external data directly into a selected HTML element of our page using jQuery AJAX methods.
Here in the below example we have myPage.html file which will invoke the jQuery AJAX method to load the data from another HTML file called myData.html
Make sure that you have jquery-1.8.2.js saved under the folder script.
myPage.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>j2eereference.com - jQuery Ajax </title> <style type="text/css"> body{ width: 400px; margin: 50px auto; } #myDiv{ width: 400px; height: 150px; background-color: #999999; color: #333333; } button{ width: 400px; } </style> <script type="text/javascript" src="script/jquery-1.8.2.js"></script> <script type="text/javascript"> $(function(){ $("#myBtn").click(function(){ $("#myDiv").load("myData.html a:eq(0)", function(response,status,xhr){ if(status == "error"){ alert(xhr.statusText) } }); }) }) </script> </head> <body> <div id="myDiv"></div> <button id="myBtn"> Get Data</button> </body> </html> |
myData.html
1 2 3 4 5 6 7 8 9 10 |
<html> <head> <title> Hello i am the details page </title> </head> <body> <div id="MainContent">Hello every one I am the Main Content</div> <a name="ajax" href="http://wwww.j2eereference.com">j2eereference.com</a> <a name="jQuery" href="http://209.97.166.197/2012/12/adding-css-using-jquery/">Adding css using jQuery</a><br/> </body> </html> |
Output:
Here you can notice that when you click on Get Data button , You are getting data from myData.html.
$(“#myBtn”).click(function(){ //This will trigger the click action on myBtn
$(“#myDiv”).load(“myData.html a:eq(0)”, function(response,status,xhr){ // will load the value of first Anchor tag in data .html
if(status == “error”){
alert(xhr.statusText)
}
});
})
Dimitris says
January 28, 2013 at 7:40 pmConcise and simple. Nice…