It just takes 15 seconds. Send your
details and we’ll get back to you soon.

Accessing remote data through cross-domain ajax call in jquery

While developing a mobile app using phonegap ( or otherwise also :) ), we can access remotely hosted mysql database using jquery ajax calls. But this interaction between jquery and mysql database cannot happen directly. We will need to specify a server side script(in PHP terminology) or a controller action(in Grails Terminology) that will fetch data from the mysql database and serve it to the jquery call. Jquery will simply make a cross-domain ajax request to the server side script and the script will send requested data as response.

For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call.
JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.

When we specify dataType as jsonp, a “callback” parameter is appended to the request url and jquery creates a function whose name is the value of callback parameter. On server side, the script receives the “callback” parameter value(which is name of the function) and sends the data as argument to that function. Alternatively, that data is also available in the success function of jquery.

Jquery Code :

	    function crossDomainCall(url,data,fnSuccess,fnError){
            $.ajax({
                type:'POST',
                url:url,
                contentType:"application/json",
                dataType:'jsonp',
                crossDomain:true,
                data:data,
                success:fnSuccess,
                error: fnError
            });
        }
	
        function authenticateUser(username, password) {
            var url = 'http://www.example.com/user/authenticate';
            var data={username:username, password:password};
            var fnSuccess=function (dataReceived) {
		    if(dataReceived) {
			    alert("Welcome "+dataReceived.name);
		    }else{
			    alert("Authentication failed")
		    }
            };

            var fnError=function (e) {
                alert(e);
            };
            crossDomainCall(url,data,fnSuccess,fnError);
        }

Server side code :

 
	def authenticate(String username, String password){
        	User user=User.findByNameAndPassword(username,password)
		    if (user) {
		        render "${params.callback}(${user as JSON})"
		    }else{
		        render "${params.callback}(null)"
		    }
    	}

Here, the function name is received from params.callback and data is sent in json form as an argument to the function.

Hope it helps.
Have Fun :)

Share

Posted in Database, Grails, Javascript/Ajax/JQuery | Tagged , , , , , .

5 Responses to Accessing remote data through cross-domain ajax call in jquery

  1. Nadeem says:

    Hello Raj,

    I works upon grails and if i have to access grails service through a PhoneGap application than whats the configuration i have to do at the grails app end.

  2. Thznks for aany other informative web site. The place else could I get that kind of info written inn such an ideal way?
    I’ve a project that I am simply noow working on, and I’ve been on the glance out for such info.

  3. Hi colleagues, how is the whole thing, and what you desire to say on the topic of this article, in my view its genuinely awesome in support of me.

  4. Movie star and singer Patrick Bruel has been considered one of France’s biggest stars through the ’90s, first making their name being
    a teen idol and leading an excellent to traditional French chanson inside new millennium.
    Bruel was given birth to Patrick Benguigui with Tlemcen, Algeria, on,
    may 14, 1959. His father abandoned a family when Patrick was merely a year
    old, and 1962, after Algeria gained its independence,
    his mummy moved to France, settling in the Paris suburb connected with Argenteuil.
    A great soccer player within the youth, Patrick first settled on the
    idea of like a artist after seeing Michel Sardou perform in 75.

    As good fortune might have it, acting would get him his first good results; first-time movie director Alexandre Arcady ran an offer seeking a man using a French-Algerian (or “pied-noir” in People from france
    slang) accent for his video Le Coup dom Sirocco. Benguigui
    (as he was still called) responded and won the part.
    The below year, he spent a little while in New York City, where he found Gérard Presgurvic, later
    to become his most important composer.

    Source: http://proplus.hkwork.com/2013-blogs-20years/

  5. meladerm says:

    After checking out a few of the blog posts
    on your web page, I truly appreciate your way of writing a blog.

    I book-marked it to my bookmark website list and will be
    checking back in the near future. Please visit my
    website as well and let me know your opinion.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get our latest updates, Subscribe.

By signing up, you agree to our Terms of Service and Privacy Policy.

Categories