jquery with sprin mvc framework

20
jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery By Viral Patel on April 12, 2009 Tweet jQuery, the JavaScript library provides some powerful set of jQuery AJAX API’s to handle AJAX requests. The normal way of making AJAX calls using JavaScript is a bit odd as you have to first create an XMLHttpRequest object that depends on the browser and then make an AJAX call. Also sending a form data using AJAX is also bit difficult if we use normal JavaScript approach of calling AJAX. jQuery provides simple yet powerfull functions which have extended the JavaScript AJAX methods and provide more flexible way. Let us see different ways of doing AJAX things in jQuery. GET Request method using jQuery Load a remote page using HTTP GET request method. This is an easy way to send a simple GET request to a server. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). jQuery.get( url, [data], [callback], [type] )

Upload: springrk

Post on 15-Oct-2014

25 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Jquery With Sprin Mvc Framework

jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery

By Viral Patel on April 12, 2009

Tweet

jQuery, the JavaScript library provides some powerful set of jQuery AJAX API’s to handle AJAX requests. The normal way of making AJAX calls using JavaScript is a bit odd as you have to first create an XMLHttpRequest object that depends on the browser and then make an AJAX call. Also sending a form data using AJAX is also bit difficult if we use normal JavaScript approach of calling AJAX.

jQuery provides simple yet powerfull functions which have extended the JavaScript AJAX methods and provide more flexible way. Let us see different ways of doing AJAX things in jQuery.

GET Request method using jQuery

Load a remote page using HTTP GET request method. This is an easy way to send a simple GET request to a server. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code).

jQuery.get( url, [data], [callback], [type] )

url: (String) The URL of the page to load.data (Optional): (Map) Key/value pairs that will be sent to the server.callback (Optional): (Function) A function to be executed whenever the data is loaded successfully.type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”.e.g.

?010

$.get(    "http://some-remote-site",    "{key:value}",    function(data) { alert(data); },

Page 2: Jquery With Sprin Mvc Framework

2030405060708091011

    "html");

 $.get(    "http://some-remote-site",    function(data) { alert(data); },);

POST Request method using jQuery

Sending post method is also very easy with jQuery. All you have to do is just to call jQuery.post () method instead of jQuery.get (). Following is the syntax of post method.

jQuery.post( url, [data], [callback], [type] )

url: (String) The URL of the page to load.data (Optional): (Map) Key/value pairs that will be sent to the server.callback (Optional): (Function) A function to be executed whenever the data is loaded successfully.type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”.

?1234

$.post("test.php", { func: "getNameAndTime" },  function(data){    alert("Hello");  }, "json");

Get JSON using jQuery

JavaScript Object Notation (JSON) is a popular light weight format that can be used to get data from server. JSON has became very popular since that web pages have became interactive using

Page 3: Jquery With Sprin Mvc Framework

AJAX. JSON format is easy to create from the server and easy to parse at client as it is the basic object representation in JavaScript.

JQuery provides a function that can be used to make an AJAX call and get the data in JSON format. Normally the data that we get from AJAX is converted in JSON by calling eval () method of JavaScript. But the function provided by JQuery handles this internally and provides direct JSON object as output.

jQuery.getJSON( url, [data], [callback] )

?1234567

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",        function(data){          $.each(data.items, function(i,item){            $("<img/>").attr("src", item.media.m).appendTo("#images");            if ( i == 3 ) return false;          });        });

AJAX Start/End using jQuery

While you make an AJAX call and get some data from server, it is good to show a progress bar or image to user so that (s)he knows that something is going on. Hence Loading… text is common in AJAX enabled application.

What if you web application is making many AJAX calls like gmail. You may want to display a Loading… text while any of AJAX call is proceeding. To achieve this ajaxStart() and ajaxComplete() methods of jQuery can be used.

ajaxStart() method registers a function handler that will be called by jQuery internally whenever an AJAX call is made. If already a request is active than the handler is not called. We can use this method to register a handler function that will display our progress bar.

?123

$.ajaxStart(function() {    $("div#loading").text("Loading...");});

In above code snippet, we used ajaxStart() method to register a function that set the innerHTML of div to Loading…

Similarly ajaxComplete() method can be used to register a handler function which gets called by jQuery when an AJAX request get completed and any other active request are not in progress.

?1$.ajaxComplete(function() {

Page 4: Jquery With Sprin Mvc Framework

23    $("div#loading").text("");});

Serialize html form using jQuery

While submitting a form using AJAX, one has to create a input string that contains the value of all the input elements on the screen. It is very difficult to create this string if your form is very big. Hence we can use jQuery’s serialize() and serializeArray() method to do so.

serialize()

Serializes a set of input elements into a string of data. Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks. In order to work properly serialize requires that form fields have a name attribute. Having only an id will not work.

?12var str = $("form").serialize();$("#results").text(str);

In above code snippet, we created a serialize output of the form. This value can be sent to server by an AJAX call.

serializeArray()

serializeArray() does the similar job. Except it creates JSON output.

?12345

[     {name: 'firstname', value: 'Hello'},     {name: 'lastname', value: 'World'},     {name: 'alias'}, // this one was empty]

If you read this far, you should follow me on twitter here.

Related Posts

jQuery Ajax – Handling unauthenticated requests via Ajax jQuery tabs: Create HTML tabs using jQuery UI Tutorial: Handle browser events using jQuery JavaScript framework How to apply HTML User Interface Effects using jQuery. AJAX Post Method example using Javascript & jQuery Multiple Checkbox Select/Deselect using jQuery – Tutorial with Example Sum HTML Textbox Values using jQuery / JavaScript

Page 5: Jquery With Sprin Mvc Framework

Get our Articles via Email. Enter your email address.

 Tags: AJAX, JavaScript, javascript framework, JQuery, jquery ajax tutorial

45 Comments

BParker wrote on 3 July, 2009, 3:53

Excelent tutorial, direct, to the point, and in exactly the right order for developing an app!

Thanks

Reply

Name (required) wrote on 3 August, 2009, 15:27

Comment:Thank u for gooda tutorial. I got lot information about ajax using the jquery…Keep on posting these types of good tuorials…….Great work…..All the best……

Reply

soevar wrote on 6 September, 2009, 3:53

Good tutorial…

Reply

Page 6: Jquery With Sprin Mvc Framework

jquery help wrote on 6 September, 2009, 17:44

Hey,

It is a good help to me.It might be useful to me.

Reply

Ahmed Gaber wrote on 23 October, 2009, 16:09

You have collected the complete set, I like the way you’ve illustrated the methods,

and from now, I’ll use jQuery Ajax API

Reply

Gaurav Gupta wrote on 8 January, 2010, 11:08

Thanks Dear… Grt tutorials… I hv been searching for json ajax requests for a long time… gud wrk

Reply

o

Viral Patel wrote on 8 January, 2010, 15:29

@Gaurav – Thanks for the good words.

Reply

Page 7: Jquery With Sprin Mvc Framework

henrihnr wrote on 27 January, 2010, 14:07

hi, good tutorial. i would like to ask about ajaxStart and ajaxComplete methods. They are registered to every ajax call. How do we register each ajaxStart/ajaxComplete to each ajax call? suppose there are 2 section on screen that use ajax, each section requires Loading sign at specific position. or is there any technique to do this using jquery?

Thanks for your attention.

Reply

Indialike wrote on 28 January, 2010, 10:28

Very nice and useful tutorials for web designers,Thanks for posting.

Reply

ajith wrote on 2 February, 2010, 12:36

good yarrrrrrrrrrrr……….

Reply

Andy wrote on 22 February, 2010, 3:43

Great tutorial. Most tutorials get into way to many unimportant details which leaves the reader confused. This is a great way to build a foundation for using jquery to perform Ajax since I’m a jquery newb. Thanks!

Reply

Page 8: Jquery With Sprin Mvc Framework

o

Viral Patel wrote on 23 February, 2010, 15:51

@Andy: Thanks for the comment. I appreciate that you liked the tutorial. Feel free to bookmark/share this article.

Reply

Mark wrote on 9 March, 2010, 9:57

Great tutorial!

Reply

akhilesh wrote on 20 March, 2010, 11:32

thanks its really important

Reply

kb wrote on 14 April, 2010, 11:36

its powerful tutorial for starting of Ajax with jQuery.

Reply

anjali wrote on 15 April, 2010, 14:22

Page 9: Jquery With Sprin Mvc Framework

great tutorial.ur explanation is very nice and easy to understand for beginners also..

Reply

M A Hossain Tonu wrote on 5 May, 2010, 20:57

This could be a good read…http://mahtonu.wordpress.com/2010/05/05/ajax-with-jquery-ajax-jquery-api/

Reply

Vikas Parab wrote on 28 May, 2010, 17:15

Please help to fix my problem. I want to use load with post method. I am writting javascript function like below:

function test(){qString = “a:’1′,b:’2′,c:’3′$(“#objectID”).load(“test.php”, {qString} );}

the above function gives me error.Instead of variable if i write function like below, then it works properly.$(“#objectID”).load(“test.php”, {“a:’1′,b:’2′,c:’3′} );

Please let me know how I typecast qString.

Thank you.RegardsVikas Parab

Reply

Page 10: Jquery With Sprin Mvc Framework

Samir PATEL wrote on 4 June, 2010, 12:08

HI Viral,I want to merge two row having same value for whole table for perticular column. in Java script or JQ. we develoing intarnet application for my company.

Reply

Kjell wrote on 9 June, 2010, 13:54

Thanks this is just what we needed, excellent tutorial.

Reply

flazw.cz.cc wrote on 30 July, 2010, 21:17

A really very informative tutorial on the subject.

Reply

Raghib suleman wrote on 3 August, 2010, 12:07

Thank u for good tutorial…

Reply

JSX Solutions - Isle of Wight Web Design wrote on 17 August, 2010, 2:47

Real decent jquery/ajax tut cheers

Reply

Page 11: Jquery With Sprin Mvc Framework

ricky wrote on 14 September, 2010, 11:34

any working demo? thnx

Reply

Ramesh wrote on 15 September, 2010, 10:46

hi, this is nice tutorial.thanks

Reply

Onion wrote on 18 October, 2010, 12:24

Thanks, this is just what I was looking for to start using AJAX. The only other think I’d have liked was a practical example of seeing all these working together, so that I could see what the ideal AJAX project should look like.

Reply

Wally wrote on 9 December, 2010, 4:06

Thanks for the awesome tutorial. Spot on as usual. Just what i was looking for my project.

Reply

Page 12: Jquery With Sprin Mvc Framework

Zuallauz wrote on 19 December, 2010, 8:57

Thanks, good info. However passing “{key:value}” into the $.get method doesn’t work. You actually need to pass the values in as {key:value} without double quotes. E.g. {id: 1, name: “Bob”}

Reply

web design wrote on 14 February, 2011, 20:02

great tutorial….jquery is really my lovely library…thanks for sharing this.

Reply

shrikant wrote on 21 February, 2011, 12:16

nice tutorialeasy 2 understand,with easy words…thnks grt work

Reply

javaeschool wrote on 24 February, 2011, 11:41

Thx for this very helpful tutorial..It helped me in my project…:)

Reply

Deva Karthik wrote on 13 April, 2011, 11:26

Very Helpful!

Page 13: Jquery With Sprin Mvc Framework

Reply

girssss wrote on 2 June, 2011, 15:18

good ……

Reply

Irfan wrote on 20 July, 2011, 14:56

outstanding article

Reply

Parnita Das wrote on 29 July, 2011, 11:54

it really good article i am using your technique in our site

Reply

Richard wrote on 16 August, 2011, 14:04

Looks nice. I will try it out to give you a feedback soon.

Reply

Richard wrote on 16 August, 2011, 15:31

Page 14: Jquery With Sprin Mvc Framework

Easy to read, but a show about how the whole things work together under a simplified real setting would make it better.

Reply

ahmet wrote on 19 September, 2011, 14:23

thanks mate

Reply

Mark William wrote on 3 November, 2011, 17:10

Thank you so much for such a nice article.i liked it very much.Thank you for sharing. Mark

Reply

Virendra wrote on 30 November, 2011, 10:17

Bloody Awesome..

But I don’t prefer jQuery.post() or jQuery.get() method to do an ajax call as they don’t support error handling.

http://jquerybyexample.blogspot.com/2011/11/avoid-jquerypost-use-jqueryajax.html

I prefer jQuery.ajax() as it supports error handling as well.

Reply

Page 15: Jquery With Sprin Mvc Framework

Arul wrote on 26 December, 2011, 16:05

how to get local server get json values simple example please help me.example if local server path Get JSON url and data.

Reply

Arvind wrote on 10 January, 2012, 13:06

good tutorial but i use $.ajax() it is simple too…….

Reply

Golak Jena wrote on 16 January, 2012, 14:08

Very good tutorial….It’s very needful….Thanks

Reply

psharp wrote on 18 January, 2012, 4:18

BEWARE: This technique won’t work except for getting json.jquery documentation explains here (read “Additional Notes” at bottom) :http://api.jquery.com/jQuery.get/

You can spend hours chasing errors if you don’t notice this detail!!!

So VP, please at least include the warning

Reply

Page 16: Jquery With Sprin Mvc Framework

snehal wrote on 24 January, 2012, 15:15

nice 1..

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *

Email *

Website

Comment

Advertise Here

Subscribe

Get our Articles via Email. Enter your email.

Page 17: Jquery With Sprin Mvc Framework

 Follow Me

 

Latest Posts

1. Convert Arrays to Set in Java 2. STOP SOPA JQuery Plugin 3. How To Create QR Codes in Java & Servlet 4. Facebook Style Scroll Fixed Header in JQuery 5. Create ZIP Files in JavaScript 6. Play Framework Modules: Divide and Conquer 7. Hibernate Inheritance: Table Per Concrete Class (Annotation & XML mapping) 8. Hibernate Inheritance: Table Per Subclass (Annotation & XML mapping) 9. How To Reset MySQL Autoincrement Column 10. Struts 2 Tip: Override Default Theme

Your E-Mai