bhavesh
bhavesh

Reputation: 457

Want data returned by python to javascript to be accessible inside a html div

A] Technologies being used:

1] Javascript

2] Jquery (elements currently being used are Jquery tab and Jquery datatable)

3] Python

4] Google App engine

B] Problem Summary:

1] I have a javascript function that calls a python class and gives it users city and country value.

2] The python class then queries the database and finds out the particular city entry in the database and returns the object back to javascript.

3] I have a alert box in javascript and can see the object being printed successfully. I am using jquery tabs and within the tab I have a datatable.

enter image description here

4] I want the data obtained in the javascript to be usable inside the jquery tab so that the data can be printed in the datatable format

C] Code Excerpts:

1] Javascript code that calls the python class , giving it users country and city

<!-- script snippet to fill in users country and city value by making a calls to the geoip library -->  
<script type="text/javascript">
    // selecting users country and users city, 
    // the id for users country drop-down list is "id_country_name"
    // the id for users city text-box is id_city_name
    $(function () {

        //finding the users country and city based on their IP.
        var $users_country = geoip_country_name()
        var $users_city = geoip_city()

        // setting the drop-down list of country and text-box of the city to users country and city resp
        $("#id_country_name").val($users_country);
        $("#id_city_name").val($users_city);

        //since we have users country and city, calling python class to get the data regarding users country and city combination 

        $.post("/AjaxRequest", { 
                                selected_country_name: $users_country,
                                selected_city_name: $users_city  
                               },
            function(data) {
                alert(data);
            }
        );

     });

</script>

2] HTML code for jquery tabs and jquery datatable.

<div id="userReportedData">     
<!-- Setting up the tabs to be shown in the html page, not the name of the tabs div is "tabs"
     this matches with the name defined the javascript setup for jquery tabs -->
 <div id="tabs">
    <!-- defining the tabs to be shown on the page -->
    <ul>
        <li><a href="#your_city">Your City</a></li>
    </ul>

    <div id="your_city">     
         <!-- Table containing the data to be printed--> 
         <table cellpadding="0" cellspacing="0" border="0" class="display" id="datatable_for_current_users">
         <thead>
            <tr>
                <th>Country</th>
                <th>City</th>
                <th>Reported at</th>
            </tr>
        </thead>
        <tbody>
            {%for status in data_for_users_city.statuses %}
                <tr class="gradeA">
                    <td>{{data_for_users_city.country.country_name}}</td>
                    <td>{{data_for_users_city.city_name}}</td>
                   <td>{{status.date_time }}</td>
                </tr>
            {%endfor%}  
         </tbody>
        </table>        
    </div>

I want the data that is obtained by the javascript function from the python class to be accessible inside the tbody to be used.

NOTE: the for loop in the tbody isn't working, once i have the data for the "data_for_users_city" correctly loaded , then i will test this.

3] Python class which is sending the data to javascript:

class AjaxRequest(webapp.RequestHandler):

  #the string content of the template value 'all_data_from_datatabse'
  __TEMPLATE_ALL_DATA_FROM_DATABASE_FOR_USERS_CITY = 'data_for_users_city'

  def post(self):
    user_reported_country_get = self.sanitize_key_name( self.request.get("selected_country_name") )
    user_reported_city_get = self.sanitize_key_name( self.request.get("selected_city_name") )
    data_for_users_country_city = self.get_data_for_users_country_and_city(user_reported_country_get, user_reported_city_get)

    template_values = {
        self.__TEMPLATE_ALL_DATA_FROM_DATABASE_FOR_USERS_CITY: data_for_users_country_city
    }

    self.response.out.write(data_for_users_country_city)

  def sanitize_key_name(self,key_name):
    string_key_name = unicodedata.normalize('NFKD', key_name).encode('ascii','ignore')
    return re.sub(r'\s', '', string_key_name.lower())

 def get_data_for_users_country_and_city(self,users_country,users_city):
    key_name_for_user_reported_city = users_country + ":" + users_city
    return UserReportedCity.get_by_key_name( key_name_for_user_reported_city )

[EDIT#1]

javascript solution that worked

function LoadUsersDatatable(data) {
var tbody = $("#datatable_for_current_users > tbody").html(""); 
jsonData = jQuery.parseJSON(data);

for (var i = 0; i < jsonData.length; i++) 
{
        var citydata = jsonData[i]; 
        var rowText = "<tr class='gradeA'><td>" + citydata.city.country.country_name + "</td><td>" + citydata.city.city_name + "</td><td>" + citydata.status + "</td><td>" + citydata.date_time.ctime + "</td></tr>";
    $(rowText).appendTo(tbody);
     }
 }    

Upvotes: 2

Views: 2027

Answers (3)

Kevin P
Kevin P

Reputation: 1655

Javascript can't do anything with a python object, which is what is being returned via your Ajax POST right now. Before you return anything with your request handler you will want to encode the data (using either XML or JSON as mentioned by fceruti) in a way that you can then decode using javascript.

Upvotes: 0

David Mason
David Mason

Reputation: 2957

It looks like you're using a Django template in your HTML there. This is all parsed server-side so you won't be able to use the data from the object you've returned in the inline code. Instead you need to make changes through the DOM using jQuery.

You've got an ajax call there, so you'll be getting a response in xml, which you can parse with jquery.

It looks like you'll want to either add another row to the table, or replace one of the rows with the new data. If adding a row you'll need to get the table

function(data) {
    var newRow = $('<tr class="gradeA"></tr>');

    //you can use $('attributename', data) to access each attribute
    // in the returned data object

    // build tds with the data, like I've done in the line above for the tr
    // then append them to newRow, using .append()

    // then we can just append the new row to the table
    $('#your_city').find('tbody').append(newRow);
}

If you wanted to replace a row, you could do a similar thing but remove the old row first, or use jQuery to find the row you want to change things in and replace the td contents with the returned data.

Upvotes: 2

fceruti
fceruti

Reputation: 2445

You should encode your object into JSON or XML (but I prefer JSON). You can do it manually in python or using a library such as jsonpickle. Then on you javascript you can parse that string in a safe way with:

var jsonObj = JSON.parse(data);

And then when you want to access something its very easy. Lets say you have this JSON

{
"students": [
        {"name": "mark", "picture": "/a.jpg"},
        {"name" : "steve", "picture": "/b.jpg"}
    ],
"class": "Biology"
}

You can access the data like this:

> document.println(jsonObj.students[0].name)
mark

> document.println(jsonObj.class)
Biology

Upvotes: 0

Related Questions