jQuery ajax passing value/data from python script - javascript

the overall goal is to show the extract sql data on website
inside html, I'm running ajax
html
<!DOCTYPE html>
<html>
<body>
<p id="demo">original data</p>
<script type="text/javascript">
$.ajax({
type: 'POST',
url: 'get_sql_where_02.py',
data: {data_sent:'Send this to python script'},
success: function(data) {
document.getElementById("demo").innerHTML = data;
}
});
</script>
</body>
</html>
get_sql_where_02.py
import mysql.connector
import webbrowser
import time
import pymysql
import sys
import ast
mydb = mysql.connector.connect(
host="196.8.98.141",
user="root",
password="password",
database="data_db",
auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
mycursor.execute("SELECT P_NAME,P_PRICE FROM webpage WHERE P_ID = '001'")
myresult = mycursor.fetchall()
print(myresult)
data_to_pass_in = myresult
input = ast.literal_eval(sys.argv[1])
output = input
output['data_returned'] = myresult
sys.stdout.flush()
Question: why I don't get the feedback from py script?
pic with no feedback from py script

Related

Including JS file returns html content

I am facing this problem, and i cannot figure it out. Its simple thing, i need to include my js file into a head. But in my page I've got error Uncaught SyntaxError: Unexpected token '<' in ShopData.js:1 . So I've checked that file in chrome inspector, and i see that there is no JS content inside of it. It basically clone the html file and include it as js. How this can even happen and what is the solution? In ShopData.js is pure JS content, no includes or something. I've already checked permissions for that files and set it to read/write but no result, whole page is in domain hosting. Thanks for any advice.
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="ShopData.js"></script>
</head>
JS File:
var ShopID = 0;
var Name = "";
var City = "";
var Street = "";
var PostCode = "";
var State = "CZ";
var Longitude = "";
var Lattitude = "";
var Email = "";
var Telephone = "";
var Tittle = "";
var Description = "";
var Keywords = "";
var Barbers;
var OpeningHours;
var ItemTypes;
var Items;
let ShopData = {};
jQuery.ajax({
type: "GET",
url: "https://example.com/",
dataType: "json",
success: function(response) {
console.log(response);
}
});
Screenshot of response
This file isn't valid JavaScript so it will give that error:
https://barber.minuto.cz/web/ShopData.js
Also it seems to give that response no matter which URL you type in:
https://barber.minuto.cz/web/asdfasdf
Also you may want to make it so everyone can't login here since it is out in public now:
https://barber.minuto.cz

Getting no data when converting Python API call to Javascript and HTML

This is going to be a very generic question, so apologies in advanced. I have a python API call that I am trying to 'convert' to JS and HTML so I can create a dashboard with the data. What it does is display one numerical piece of data which we may assume is "500".
Here is my Python class which works perfectly:
url = 'https://someURL'
headers = {
"Authorization":"Bearer XXXX-XXXX",
"Content-Type":"application/json"
}
r = requests.get(url, headers=headers)
result = r.json()
print(result['Power'])
This returns a number from the API. Again, let's pretend it's "500". Now ere is my attempt at the JS: mainJS.js
var app = angular.module('tabletApp',[]);
app.controller('tabletCtrl',function($scope, $interval, $http){
var dataType = "json";
$scope.getData = function(){
var req = {
method: 'POST',
url: "https://XXXX",
headers: {
'Content-Type': 'application/json',
'Authorization':'Bearer XXXX',
data: postBody
};
$http(req).then(function(response) {
var data = response.data.result['consumptionPower'];
$scope.kw = response.data.result['consumptionPower'];
$scope.cost = calculateTouCost($scope.kw);
},
function(data) {
console.log(data);
});
}
$scope.getData();
$interval($scope.getData,10000);
});
And here is the supporting HTML to display the data in a webpage. index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="mainJS.js"></script>
</head>
<body class="black" ng-app="tabletApp" ng-controller="tabletCtrl">
<div class="container center" class="black" >
<center><p><b><h1>ACTIVE WATTS FROM API: {{kw}}</h1></b><p></center>
</div>
</body>
</html>

flask python,javascript variable issue?

my flask code section that have issue
main.py
from flask import Flask, render_template, url_for
import pandas as pd
import json
app = Flask(__name__)
#app.route('/')
def home():
df = pd.read_csv('test.csv')
df = df.groupby('name')['marks'].sum()
j = df.to_json(orient='index')
return render_template("work.html",s=j)
if __name__ == "__main__":
app.run(debug=True)
and i want to pass j into my javascript file that is look like that
work.js
//pie chart
var s = {{ j|safe }};
var keys = [];
for(var k in s) keys.push(k);
var value = [];
for (var k in s) value.push(s[k]);
var data = [{
values: value,
labels: keys,
type: 'pie'
}];
var layout = {
height: 400,
width: 500
};
Plotly.newPlot('myDiv1', data);
work.html
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="navbar"><span>data representation with Plotly.js</span></div>
<div class="wrapper">
<div id="myDiv1"></div>
<script type="text/javascript" src={{ url_for('static', filename='work.js')}}>
</script>
</div>
</body>
</html>
how to pass j variable in flask to s variable in javascript file that render with html page and show right content or say that no graph shown
Thank you
You can't do that. You have to return that json in your flask method and make an ajax request from javascript.
from flask import jsonify
#app.route('/')
def home():
j = df.to_json(orient='index')
return jsonify(j)
I don't know if flask has something like JsonResponse as django has. If yes you should use that like: return JsonResponse(j)
$.ajax({url: "your_url", success: function(result){
//result is what you returned from flask
}});

Fusion Tables MAXIMUM QUERY set data to 0 IF return no row

Hello I want to set my data value to 0 if my query result no row or data undefined. I tried change the dataType, error, done, succees and set header to
header('Content-Type: application/json');
Blockquote
but not worked.
Can anybody help me? thanks for any help..
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Fusion Tables Layer Example: Basic JSONP Request</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
function jp() {
var query = "SELECT MAXIMUM ('Tinggi Pohon') FROM 1O5aIPnHBCimWsYg0gOXIeRH6eL-6byD95Nd2pdXR WHERE idStatistikPohon=0 ";
var encodedQuery = encodeURIComponent(query);
// Construct the URL
var url = ['https://www.googleapis.com/fusiontables/v1/query'];
url.push('?sql=' + encodedQuery);
url.push('&key=AIzaSyA6Lug89RBK8spwEEq1WYrrzbDwlsgUrK0');
url.push('&callback=?');
// Send the JSONP request using jQuery
$.ajax({
url: url.join(''),
dataType: 'jsonp',
success: function (data) {
response = jQuery.parseJSON(data);
var rows = data['rows'];
var ftData = document.getElementById('ft-data');
var tpv = rows[0][0];
if(tpv != null){
ftData.innerHTML = "Total "+tpv+" data";
}
}
});
}
</script>
<script type="text/javascript">
function initialize() {
jp();
}
</script>
</head>
<body onload="initialize()">
<div id="ft-data"></div>
</body>
</html>
success: function (data) {
//set data to an empty object when it's undefined
var data=data||{};
//set default for rows when it's undefined
var rows = data['rows']||[[[0]]];
var ftData = document.getElementById('ft-data');
var tpv = rows[0][0]
if(tpv != null){
ftData.innerHTML = "Total "+tpv+" data";
}
}

How to move a javascript function from an html file to a js file and call it from the html?

Javascript newbie here. I have a javascript function that works nested in an html file, I import an external library abaaso, then declare the function and then call it:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script src="abaaso.js"></script>
</head>
<body>
<script>
var baseurl = "https://example.com";
var baseapi = baseurl + "/api/v1/";
var api_username = "user";
var api_key = "key";
var credentials = "?api_username=" + api_username + "&api_key=" + api_key;
var rawdata = {};
(function ($$) {
/* login */
login = function(username, password) {
var calledUrl = baseapi + "user/login/" + credentials;
calledUrl.post(
function (content) {
/*console.log("success" + JSON.stringify(content, null, 4));*/
},
function (e) {
console.log("it failed! -> " + e);
},
{
"username": username,
"password": password
},
{"Accept" : "application/json"}
);
}
})(abaaso);
login('test#example.com', 'passwd');
</script>
</body>
</html>
I want to put it in an external .js file and import it and only use the call to the function login('test#example.com', 'passwd');. I don't want to import abaaso from the html file but from the new .js.
How can I do that? Is there a particular structure to respect? Do I need to create a global function to the js file?
I don't want to import abaaso from the html file but from the new .js.
You can't do that. However, you can import both abaaso and the new .js:
<head>
<title>title</title>
<script src="abaaso.js"></script>
<script src="new.js"></script>
</head>

Categories