Saturday 22 October 2011

AJAX & Web.py : how to load a data from a server by using jQuery.get() method.

We have already discussed some basic ideas about ajax and web.py in the previous post ,so now we are going to discuss some more functions that you can perform with ajax.

The Jquery.get() method is used to perform AJAX HTTP GET request.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 completed.


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


url          :  The corresponding URL to load.
data        :  key/value pair that will be send to the sever (*optional).
callback :  (Function) A function to be executed whenever the data is loaded successfully (*optional).
type        :  Type of data to be returned to callback function "xml","html","script","json" etc (*optional).


Now lets look at the working of JQuery.get() method here with the help of an example.


Qn: create a web.py URL that should return a random number between 1 & 1000,and create another URL it should display a text box and a button,when you hit the button,random numbers should be displayed inside the text box.


Before we are going to start You have to create a directory named static in the same folder where you are going to create this application.The HTML template will put in this directory.
First of all you all know that you have to map the URL's to the corresponding classes,here the root URL will map to 'rand_num' class and the second URL ('/random') will map to the 'return_num' class.

If we are using any HTML templates you have to define it by using the line 'render=web.template.render('template/'),then only it can fetch the code from the template directory,that why we already created a directory called template.


our web.py program displayed below.


program name : random.py


import web
import random

urls = (
    '/', 'rand_num',
    '/random','return_num')

app = web.application(urls, globals(), True)
render = web.template.render('templates/')


class rand_num:
    def GET(self):
      return render.random()

class return_num:
    def GET(self):
      return  random.randint(1,1000)

if __name__ == "__main__":
    app.run()


Then we have to define the class('/rand_num') for the root URL. the root URL should have to display a text box and a button,so that you have to call the corresponding HTML template ,here the method render.random() will returns a rendering of the HTML template 'random'.you have to specify the exact name of the html template that located in the templates directory here to fetch it from the directory when the code runs.


After that we have to define the class ('return_num') for the random number generation i.e when the browser get form this URL,it should return a random number between 1 - 1000 .We have a module in python called random ,by importing this module we can call random.randint() method to get random numbers between certain ranges,here we can use random.randint(1,1000) to get the random numbers between 1-1000.


Now lets look at the html template 'random.html' located in the templates directory.


<html>
        <head>
        <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
        
        <script type="text/javascript">
        jQuery(document).ready(function(){
        jQuery("button").click(function(){
          jQuery.get("/random",function(result){
             jQuery("#text1").val(result);
          });
        });});
        </script>
        </head>

        <body>

        <input type = "text" id = "text1" />

        <h2>Hit the button to view random numbers</h2>

        <button>Click</button>

        </body>
</html>


Here the url ("/random") specified in the jQuery.get() method specifies the corresponding url to load.and then the callback function specified here will execute when the data is loaded successfully.


Here when we press the button the jQuery.get() method will invoke and it will load the url "/random'.we have already defined the "return_num" class for the "/random" url that ,it returns only a random number between 1-1000.So when the data i.e (random number) is loaded successfully,then the callback function will execute and variable name "result" will contain the returned value.Then finally we just displayed it inside the text box.

1 comment:

  1. Thank you Sreehari - I find this post very useful.
    Do you have samples of jQuery POST? Basically I want to pass multiple input values to back-end and get some result.
    -Reshmi

    ReplyDelete

Note: only a member of this blog may post a comment.