JQuery and python script



Recently i have implemented JQuery in one of the site created through python CGI. I googled a lot about it and got very easy solution to this.
I guess, this can be used in any site where we need to call python script.

 

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
$("#AnyID").click(function()
    {
        $.ajax({
            type: "get",
            url: "<your-python-script>.py",
            data: {'param1':'abc'},
            datatype:"script",
            async: false,
            success: function(response) {
            // response is string, convert it to json and apply conditions.
            var json_obj= eval('(' + response + ')');//$.parseJSON("'"+response+"'");
            if (json_obj.type == 'Error'){
              alert(json_obj.msg);
            }
            else {
              alert(json_obj.msg);
            }// else closed
            }, // success closed
            error:function(xhr,err)
            {
                alert("Error connecting to server, please contact system administator.");
            }
        })//ajax closed
}
 


make sure that your python script is callable through url ex. www.example.com/<your-python-script>.py
What i did is, in my <your-python-script>.py script i return dictionary object like {'type':'Success', 'msg':'Your message'}.
If you have CGI script, dont return anything just print the dictionary.

JQuery ajax for python only supports get method for now (i found somewhere, i tried with POST, not working).
here, in above code, you can see "async:false", the purpose of it is very interesting.
While your JQuery run python script and fetch data for you, if you want to block any click event, use "async:true", interesting.. isn't it?




Leave comments

authimage
  • Query sounds like an overkill for an ajax request. It only takes a few lines of js code to implement it natively. And post works perfectly.

    • c00der
  • Very thorough, nice :)

    • Dann
  • I'm trying to make a 2D plor using data from python using an array [x 1, y1, x 2, y2] but I can't generate the graph, what am I doing wrong?

    • Miguel

Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved