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

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 ??

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);

Related

Object of type 'Query' is not JSON serializable

This is my routes.py
#app.route('/test', methods=['POST', 'GET'])
def test():
# form = BrandChoice()
# email = request.form['email']
# name = request.form['name']
choice = request.form['choice']
print(choice)
q = session.query(Brand.brand).filter(Brand.pid == choice)
print(q)
return jsonify({'choice': q })
And this is my test.js file
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
name : $('#nameInput').val(),
email : $('#emailInput').val(),
choice : $('#brandInput').val()
},
type : 'POST',
url : '/test'
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
$('#errorAlert').text(data.choice).show();
$('#successAlert').text(data.name).show();
// $('#errorAlert').hide();
}
});
event.preventDefault();
});
});
I don't quite get why is it that I cannot get the query result to show up. If I were to replace my 'q' with name for example, it works as intended.
How do I go about returning my query result so that I can display it in my errorAlert?
Thank you for the help everyone. I understand the issue with my code right now. q is a Query object. I did not even execute the query.
type_pid = session.query(LenSize.type_pid).filter(LenSize.pid == choice)
type_pid_result = session.execute(type_pid)
type_pid_count = type_pid_result.first()[0]
print(type_pid_count)
q = session.query(Type.initial).filter(Type.pid == type_pid_count)
print(q)
result = session.execute(q)
print(result)
id_count = result.first()[0]
print(id_count)
return jsonify({'name': id_count})
The amendments I have made was to execute my query and in return I would get a result proxy. Apply the first() method to obtain my desired output. That output was JSON serialisable. No changes were really made to my js file. A simplified version of my correction is below. Hope this helps!
q = session.query(Model.id).filter(Model.pid == choice)
result = session.execute(q)
row_id = result.first()[0]

YQL AJAX cross domain request stopped working

I have been using the following code to successfully read the contents of an external webpage as a string - I haven't used this program in a month or so but it has suddenly stopped working even though the code has not been changed. I suspect the YQL API has been updated but I couldn't find any documentation that I could understand on this. (I am a beginner at JS). If someone could point me to how to update my code it would be much appreciated!
Code:
function formSubmitted(raceID) {
if(raceID.length < 4 && raceID > 0){
savedRaceID = raceID;
raceUrl = "http://www.bbk-online.net/gpt/lap"+raceID+".htm";
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0].replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
//THE ERROR IS COMING FROM ABOVE - REPLACE IS BEING CALLED ON A NULL OBJECT??
//SUGGESTS NO DATA RETURNED?
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: raceUrl,
type: 'GET',
success: function(res) {
processData(res.responseText);
}
});
}
else{
alert("Please enter a valid race number...");
}
}
I have highlighted where the error is coming from - it appears that the function is not returning any data?

HTTP error "AUTH_CSFR_ERROR" with POST to Todoist API via Google Apps Script

I'm attempting to query items out of the Todoist API from Google Apps Script, mimicking a curl POST.
I originally tried to make OAuth2 work, but tokens were not persistent, and I instead opted for the API's method of using individual API tokens to exchange for a valid token.
Using App Script's UrlFetchApp class, I'm attempting to construct at POST request for Todoist's API to retrieve task items, and my getTodoistToken() function is indeed retrieving a valid token response, but the POST command is issuing the following 403:
"error_tag":"AUTH_CSRF_ERROR","error_code":0,"http_code":403,"error_extra":{"access_type":"web_session"},"error":"AUTH_CSRF_ERROR"}
Can anyone recommend a solution? Thanks so much, code below:
function getTodoistToken() {
var url = "https://todoist.com/api/access_tokens/migrate_personal_token";
var data = {
"client_id": "[my unique client_id]",
"client_secret": "[my unique client_secret]",
"personal_token":"[my API token from Todoist dashboard]",
"scope": "data:read"
};
var payload = JSON.stringify(data);
var headers = {
"Content-Type":"application/json",
};
var options = {
"method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
return(data.access_token);
}
function getTodoistTasks(){
var apiURL = "https://todoist.com/API/v7/sync";
var data = {
"token" : getTodoistToken(),
"sync_token" : '*',
"resource_types" : '["items"]'
};
var payload = JSON.stringify(data);
Logger.log(payload);
var headers = {
"Content-Type":"application/json",
};
var options = {
"method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload,
"muteHttpExceptions" : true
};
var response = UrlFetchApp.fetch(apiURL, options);
Logger.log(response.getContentText());
}
I have figured out the answer. The Todoist API documentation is bit ambiguous, seeming written around POST requests, but to download (sync) a full list of tasks, a simple URL-encoded GET request, as constructed below, did the trick:
function getTodoistTasks(){
var apiURL = "https://todoist.com/API/v7/sync";
var queryString = "?token=" + getTodoistTokenRev() + "&sync_token=%27*%27&resource_types=[%22items%22]";
//Get params
var fetchParameters = {};
fetchParameters.method = 'get';
fetchParameters.contentType = 'x-www-form-urlencoded';
fetchParameters.muteHttpExceptions = true;
//make request and return
var response = UrlFetchApp.fetch(apiURL + queryString, fetchParameters);
var syncData = JSON.parse(response.getContentText());
return(syncData);
}
And if anyone is looking for an example of creating an item (a task in this case), as I was, here's the code for that (note you need to specify a date_string and due_date for it to appear in the web UI):
var API_URL = "https://todoist.com/API/v7/sync"
var BASE_QUERY = "?token=" + TOKEN
function addTask() {
// var taskName = SpreadsheetApp.getUi().prompt('What the task\'s name?')
var taskName = 'Test 1652'
var commands = encodeURI(JSON.stringify([{
"type": "item_add",
"temp_id": uuidv4(),
"uuid": uuidv4(),
"args": {
"content": taskName,
"date_string": "today",
"due_date_utc": "2017-12-2T18:00",
}
}]))
var queryString = BASE_QUERY + '&commands=' + commands
var options = {
method: 'post',
contentType: 'x-www-form-urlencoded',
muteHttpExceptions: true}
var response = UrlFetchApp.fetch(API_URL + queryString, options)
if (response.getResponseCode() !== 200) {
var content = response.getContentText()
throw new Error('URL fetch failed: ' + content)
}
var syncData = JSON.parse(response.getContentText())
return syncData
// Private Functions
// -----------------
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
} // addTask()

Jquery post response not available

I'm new to javascript, and this problem may be trivial but I need help.
My goal is to send a post to a python server based on tornado.
In the following function :
var machin = $.post( '/room/testroom', function( data ) {
truc = data;
return truc;
I never get back the content of truc.
This variable has an url inside it who will be used to create a new Websocket connection.
When I do console.dir(machin); I see the wanted responseText with the wanted url in the console, but I'm not able to get it outside of the console.
The variable data itself inside the function has my wanted data, as if I do :
alert(data)
I see an alert box with the wanted url.
Feel free to ask me for details as I may not be entirely clear.
Server side, my python code is this one:
def post(self, RoomName):
print 'je poste'
db = connect(host=config.SQLSERVER, user=config.SQLUSER, passwd=config.SQLPASS, db=config.SQLDB)
cursor = db.cursor()
uri = self.request.uri
url = uri.split('/')
RoomName = url[2]
sql = 'SELECT RoomID FROM abcd_un WHERE RoomName = %s', [RoomName]
cursor.execute(*sql)
RoomID = cursor.fetchone()
print 'RoomID', type(RoomID)
RoomID = str(RoomID[0])
RoomID = RoomID.decode()
fullurl = 'ws://' + self.request.host + '/socket/' + RoomID
#print uri
db.close()
wsurl = {
'url': fullurl,
}
wsurl_encoded = tornado.escape.json_encode(wsurl)
self.write(wsurl_encoded)
Try:
var machin = function (){
$.post( '/room/testroom', function( data ) {
truc = JSON.parse(data);
return truc;
}
Now call the function:
var response = machin();
Try:
var machin;
$.post( '/room/testroom', function( data ) {
machin = JSON.parse(data);
return True;
})

Cant get ajax response to place nice with python code

Question: For some reason I can't seem to figure out why my ajax call will not return a value for success if my wo_data query comes up empty. What I want to happen is if I put a value into id_work_order and its not found in my db pop up an alert saying workorder was not found- otherwise if it is found return success which works. Any help would be greatly appreciated!
What happens is I get this if a workorder is not found in my browser console
typeerror: data[0] is undefined
if it is found I get this
success
Here is what my data looks like if the workorder is found in my response
0: object
purch_order: "1"
success: "success"
part_rev: "A"
part_number: "12345"
work_o: "W0000001"
customer_name: "TEST"
if it isn't found I get nothing back in my response
here is my views.py
def get_work(request):
if request.is_ajax():
q = request.GET.get('workorder_id', '')
wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
results = []
for x in wo_data:
x_json = {}
if wo_data.exists():
x_json['success'] = 'success'
x_json['work_o'] = x.base_id
x_json['customer_name'] = x.name
x_json['part_number'] = x.part_id
x_json['part_rev'] = x.part_rev
x_json['purch_order'] = x.customer_po_ref
results.append(x_json)
else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)
else:
data = 'fail'
return render(request, 'app/sheet_form_create')
here is my workorder_ajax.js
$(document).ready(function () {
//$('#id_work_order').click(function () {
// getwork();
//});
$('#work_search').click(function () {
pop_other_fields();
});
//function getwork(){
// $('#id_work_order').autocomplete({
// source: "/sheet/sheet_form_create.html/get_work",
// minLenght: 2,
// });
//}
function pop_other_fields() {
var url = "/sheet/sheet_form_create.html/get_work?workorder_id=" + $('#id_work_order').val();
var work_order = document.getElementById('id_work_order').value;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
data: '',
success: function (data) {
if (data[0].success = "success") {
console.log(data[0].success);
$('#id_customer_name').val(data[0].customer_name);
$('#id_part_number').val(data[0].part_number);
$('#id_part_revision').val(data[0].part_rev);
$('#id_purchase_order').val(data[0].purch_order);
}
if (data.success = "workorder_not_found") {
alert("workorder not found :(")
}
}
});
}
});
the code here is never reached:
else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
because if if wo_data.exists(): is not true, then for x in wo_data: would never have any iterations in the first place.
Try:
def get_work(request):
if request.is_ajax():
q = request.GET.get('workorder_id', '')
wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
results = []
if wo_data.exists():
for x in wo_data:
x_json = {}
x_json['success'] = 'success'
x_json['work_o'] = x.base_id
x_json['customer_name'] = x.name
x_json['part_number'] = x.part_id
x_json['part_rev'] = x.part_rev
x_json['purch_order'] = x.customer_po_ref
results.append(x_json)
else:
results.append({'success': 'workorder_not_found'})
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Categories

Resources