Ratha
Ratha

Reputation: 9692

How to read a python dictionary from the Jquery?

My python function returns a dictionary value for My Jquery GET call.

{'Site4': {'machine': 'null', 'state': 'unprocessed'}, 'Site2': {'machine': 'null', 'state': 'unprocessed'}, 'Site3': {'machine': 'null', 'state': 'unprocessed'}, 'Site1': {'machine': 'null', 'state': 'unprocessed'}}

I want to show this in a html table Site/machine/state values separately. I get the whole dictionary from My GET call.

My Jquery function is; as follows

function loadDoc() {
    var request;
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      request = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
      } 
      catch (e) {
        try {
          request = new ActiveXObject('Microsoft.XMLHTTP');
        } 
        catch (e) {}
      }
    }
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
             var myObject = JSON.parse(this.responseText);
             alert(myObject);
          document.getElementById("demo").innerHTML =
          this.responseText;
        }
      };
    request.open('GET', 'http://localhost:8080/cache/getSite?clientName=testclient', true);
    request.send();
}

In the above the JSON.parse is not parsing the dictionary. How can I read a python dictionary value in jquery and show in a table with 3 columns for site/machine/state?

My html is;

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
}
</style>
<meta charset="UTF-8">
<title>Client Site Info</title>
</head>
<body>
<p id="demo"><button type="button" onclick="loadDoc()">load sites</button></p>
<table style="width:100%">
<caption>Client Site Info</caption>
  <tr>
    <th>Sites</th>
    <th>Machines</th> 
    <th>ProcessingState</th>
  </tr>
</table>
</body>

Upvotes: 2

Views: 2725

Answers (5)

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

$.ajax({
    type: 'POST',
    url: '',
    dataType: 'json',
    success:function(response){
        $("#loading").hide();
        if(response['success']== true){
            var dict_data = eval('(' + response['responseText'] + ')');

            $("#loading").hide();
        }
        else{
            alert("Problem in adding project in select box.");
        }
    },
    error: function (xhr, desc, err) {
        console.log(xhr);
        console.log("Desc: " + desc + "\nErr:" + err);
        $("#loading").hide();
    }
});

Upvotes: 1

user7236255
user7236255

Reputation:

var _map = {
  'Site4': {
    'machine': 'null',
    'state': 'unprocessed'
  },
  'Site2': {
    'machine': 'null',
    'state': 'unprocessed'
  },
  'Site3': {
    'machine': 'null',
    'state': 'unprocessed'
  },
  'Site1': {
    'machine': 'null',
    'state': 'unprocessed'
  }
};

$.each(_map, function(key, value) {
  $.each(value, function(x, y) {
    $('body').append(key + ' ' + x + ' ' + y + '<br />')
  });
});

output:

Site4 machine null
Site4 state unprocessed
Site2 machine null
Site2 state unprocessed
Site3 machine null
Site3 state unprocessed
Site1 machine null
Site1 state unprocessed

JSfiddle code

Upvotes: 1

A. Iglesias
A. Iglesias

Reputation: 2675

You can do it with $.ajax jquery function, specifying that you're response will be in JSON format, so you won't need to parse it.

Looking at your HTML code, I assume you want to add the results to the table, so you can create the rows and add it to the table in the success function of the ajax call...

$('p#demo button').click(function() {

    $.ajax({
        type: 'GET',
        url: 'http://localhost:8080/cache/getSite?clientName=testclient',
        dataType: 'json',
        success: function(data) {
            var rows = [];
            $.each(data,function(id,value) {
                rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
            });
            $('table').append(rows.join(''));
        }
    });
});

NOTE: Remember to remove the onclick attribute in your button...

<p id="demo"><button type="button"">load sites</button></p>

I hope it helps

Upvotes: 0

arshovon
arshovon

Reputation: 13661

To test the environment I have set up a flask application. To make JSON.parse works correctly in jQuery, I used json.dumps in python file. Here are the files:

app.py:

import json
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
@app.route('/data')
def get_data():
    data = {'Site4': {'machine': 'null', 'state': 'unprocessed'}, 'Site2': {'machine': 'null', 'state': 'unprocessed'}, 'Site3': {'machine': 'null', 'state': 'unprocessed'}, 'Site1': {'machine': 'null', 'state': 'unprocessed'}}
    return json.dumps(data)

@app.route('/table')
def show_table():
    return render_template("table.html")


if __name__ == '__main__':
    app.run(debug=True)

In templates folder the table.html contains:

<!DOCTYPE html>
<html>
<head>
    <style>
    table, th, td {
        border: 1px solid black;
    }
</style>
<meta charset="UTF-8">
<title>Client Site Info</title></head>
<body>
    <p id="demo"><button type="button" onclick="loadDoc()">load sites</button></p>
    <table style="width:100%" id="table_data">
        <caption>Client Site Info</caption>
        <tr>
            <th>Sites</th>
            <th>Machines</th> 
            <th>ProcessingState</th>
        </tr>
    </table>
    <script
    src="https://code.jquery.com/jquery-3.2.1.min.js"
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous">
</script>
<script type="text/javascript">
    function loadDoc() {
        var request;
            if (window.XMLHttpRequest) { // Mozilla, Safari, ...
                request = new XMLHttpRequest();
            } else if (window.ActiveXObject) { // IE
                try {
                    request = new ActiveXObject('Msxml2.XMLHTTP');
                } 
                catch (e) {
                    try {
                        request = new ActiveXObject('Microsoft.XMLHTTP');
                    } 
                    catch (e) {}
                }
            }
            request.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var myObject = JSON.parse(this.responseText);
                    for(key in myObject){
                        new_row = "<tr>";
                        new_row += "<td>";
                        new_row += key;
                        new_row += "</td>";
                        new_row += "<td>";
                        new_row += key["machine"];
                        new_row += "</td>";
                        new_row += "<td>";
                        new_row += key["state"];
                        new_row += "</td>";
                        new_row += "</tr>";
                        $('#table_data tr:last').after(new_row);
                    }
                }
            };
            request.open('GET', 'http://127.0.0.1:5000/data', true);
            request.send();
        }
    </script>
</body>
</html>

Output looks like:

Output

Upvotes: 2

JavidRathod
JavidRathod

Reputation: 483

var data = '{"Site4": {"machine": "null", "state": "unprocessed"}, "Site2": {"machine": "null", "state": "unprocessed"}, "Site3": {"machine": "null", "state": "unprocessed"}, "Site1": {"machine": "null", "state": "unprocessed"}}';

var obj = $.parseJSON(data);
  $.each(obj, function() {
      console.log(this['machine']);
      console.log(this['state']);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions