Ankita Dhawale
Ankita Dhawale

Reputation: 211

Making a POST request with jQuery+HTML to display JSON data

I want to display json data on frontend but after post request though it is successful it's giving specific data I need to generalize the code.This is python code.

import json
from flask import Flask, render_template, request, jsonify
import requests
app = Flask(__name__)

def post(url, payload):
    returnData={}

    if url == 'http://api/my-general-api':
        r = requests.post(url, data=json.dumps(payload))
    else:
        r = requests.get(url)

    #r = requests.get()
    if r.status_code == 200:
        returnData["status"] = "SUCCESS"
        returnData["result"] = json.loads(r.text)
    else:
        returnData["status"] = "ERROR"

    return returnData

def processSingleHost(perfid, hostname, iteration):
    hostsData = {}
    payload = {
        "perfid" : perfid,
        "section" : {
            "hostname" : hostname,
            "iteration" : iteration,
            "sectionname" : "sysstat_M"
            }
    }
    returnData = post('http://api/my-general-api', payload)
    payload = {
                "perfid" : perfid,
                "section" : {
                    "hostname" : hostname,
                    "iteration" : iteration,
                    "sectionname" : "sysstat_x_1sec"
                    }
            }
    returnData1 = post('http://api/my-general-api', payload)
    return {
        "status" : "SUCCESS",
        "sysstat_M" : returnData,
        "sysstat_x_1sec" : returnData1
    }

@app.route("/",methods=['GET','POST'])
def home():
    if request.method == 'POST':
        #user inputs
        value1 = request.form.get('perfid')
        value2 = request.form.get('hostname')
        value3 = request.form.get('iteration')
        #api call 
        url1 = 'http://api/my-general-api'/{0}'.format(value1)
        payload= {}
        rdata = post(url1,payload)
        hostsData = {}
        if rdata["status"] == "SUCCESS":
            for item in rdata["result"]:
                for host in item["hosts"]:
                    hostsData[host["hostname"]] = processSingleHost(value1,host["hostname"], 1)       //here hostname contain specific value for specific host
        else:
            return "";

        return jsonify(hostname=hostsData);   // returning all host values 

    return render_template('index.html')





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

This is my .js file for accessing data :

    $(document).ready(function() {
  console.log("ready!");


  $('form').on('submit', function() { 

    console.log("the form has beeen submitted");

    // grab values
    valueOne = $('input[name="perfid"]').val();
    valueTwo = $('input[name="hostname"]').val();
    valueThree = $('input[name="iteration"]').val();


    console.log(valueOne)
    console.log(valueTwo)
    console.log(valueThree)



    $.ajax({
      type: "POST",
      url: "/",
      dataType:'json',
      data : { 'perfid': valueOne,'hostname': valueTwo,'iteration': valueThree},
      success: function(data) {



        var x = parseInt(data.hostname.sysstat_M.result.sectoutput.summarystats.Avg.AVG); //here hostname is variable I am planning to use that will help to generalize access.

        if(x>80)
            {

                var p = '<p><div class="isa_warning"><i class="fa fa-warning"></i>CPU may be overloading.</div></p>';

                $('#result').append(p);

            }
        else
            {
                var p = '<div class="isa_success"><i class="fa fa-check"></i>CPU Usage is Normal.</div><p></p>';
                $('#result').append(p);
            }


      },
      error: function(error) {
        console.log(error)
      }
    });

  });

});

$('input[type="reset"]').on('click', function(e){
    e.preventDefault();
    $('#result').empty();
})

But as screenshot showing it demands me to make access specifically by giving hostname = 10.161.146.94/10.161.146.90

As mention in above .js

var x = parseInt(data.hostname.10.161.146.94/10.161.146.90.sysstat_M.result.sectoutput.summarystats.Avg.AVG);

But in future this hostname will be different.So I need to generalize it what can I do please suggest ??

enter image description here

Upvotes: 1

Views: 208

Answers (1)

anand
anand

Reputation: 1526

SideNote: If you are using hostname or IPs to identify each client its not adviced; since it is ought to fail.

You must use sessions for that.

Anyways, if your simply looking for how you can modify your javascript code to access the JSON response when you are not aware of the keys:

for(key in data){
    console.log(key);
    console.dir(data[key]);
}

Edit:

Showing in select box using jQuery can be done as:

var options = "";
for (key in data) {
    options += '<option value="' + key + '">' + key + '</option>';
}
$("#my_dropdown").html(options);

Upvotes: 1

Related Questions