I have the following setup. I've a simple index.html being served through apache. It looks like the following.
<!DOCTYPE html>
<html lang='en'> <meta http-equiv="content-type" content="text/html; charset=UTF8"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <canvas id="myChart"></canvas> <script language="JavaScript" src="/customcharts.js"> </script> </body> </html>
All the above does is to try and place a line chart on the browser. It uses chart.js. To accomplish this the customcharts.js tries to connect to a locally running django server. The above html is being served through apache running on port 8080 while django runs on port 8090.
the customcharts.js looks as follows
function renderChart(data){
console.log(data)
console.log(data.labels)
defaultLabels = data.labels
defaultData = data.defaultData
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: defaultLabels,
datasets: [{
lineTension: 0,
label: 'Activity Profile',
data: defaultData,
}]
}
})
}
var endpoint = 'http://localhost:8090/polls/alice/'
var defaultData = []
var defaultLabels = []
$.ajax({
url: endpoint,
dataType: "JSONP",
success: renderChart,
method: 'GET'
}
);
Further, my django view is
def json_response(func):
"""
A decorator thats takes a view response and turns it
into json. If a callback is added through GET or POST
the response is JSONP.
"""
def decorator(request, *args, **kwargs):
objects = func(request, *args, **kwargs)
if isinstance(objects, HttpResponse):
return objects
try:
data = simplejson.dumps(objects)
if 'callback' in request.REQUEST:
# a jsonp response!
data = '%s(%s);' % (request.REQUEST['callback'], data)
return HttpResponse(data, "text/javascript")
except:
data = simplejson.dumps(str(objects))
return HttpResponse(data, "application/json")
return decorator
epoch = datetime.datetime.utcfromtimestamp(0)
r = redis.StrictRedis(host='localhost', port=6379, db=0)
threat_list = ['date', 'categories', 'mix']
#json_response
def index(request, uid):
print uid
uid = uid.rstrip('/')
_key = uid
retjsondict = {}
input_keys = [_key + ':' + x for x in threat_list]
k = input_keys[0]
retdict = {}
if r.exists(k):
retvalue = r.get(k).strip('"')
xdata_dt = [x.split(':')[0] for x in retvalue.split(' ')]
ydata_dt = [x.split(':')[1].rstrip(',') for x in retvalue.split(' ')]
retdict['defaultLabels'] = xdata_dt
retdict['defaultData'] = ydata_dt
print retdict
return JsonResponse(retdict)
the index is the real view and the json_response is a decorator.
However, when I try and view it on a browser using http://localhost I get the following error
XMLHttpRequest cannot load http://localhost:8090/polls/alice/. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Could someone point to me what I'm doing off?
Any help/pointers appreciated.
If customcharts.js is within the static/yourapp you need to load your script as follows:
<script src="{% static 'yourapp/customcharts.js' %}"></script>
Don't forget to call {% load staticfiles %}
Then, a static resource can't call a view, you need to get the json data in the view and then pass it to the javascript function.
Your template should look as follows:
{% load staticfiles %}
<!DOCTYPE html>
<html lang='en'>
<meta http-equiv="content-type" content="text/html; charset=UTF8">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="JavaScript" src="{% static 'yourapp/customcharts.js' %}"> </script>
<script language="JavaScript">
$.getJSON("{% url 'index' %}", function(data) { // 'index' is the name of the view in your urls.py
renderChart(data);
});
</script>
</head>
<body>
<canvas id="myChart"></canvas>
</body>
</html>
Hope this helps.
Use 'polls' instead of 'index'
Related
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>
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
}});
I have a round slider with the slider value on client side or web page. when the user changes the slider position, the client has to send the value to the server. Here i use python flask as a server side. So the value has to be sent from j Query or java script to flask. I tried with the following code. But when i use Ajax, the web page becomes blank. It doesn't show the slider. If i remove the Ajax way of sending, the slider appears but value is not sent to server.
CLIENT SIDE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery roundSlider - JS Bin</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/jquery.roundslider/1.0/roundslider.min.css">
<script src="//cdn.jsdelivr.net/jquery.roundslider/1.0/roundslider.min.js"></script>
</head>
<body>
<div id="slider"></div>
<div id="slide"></div>
<script>
$(document.ready(function(){
var value;
$("#slider").roundSlider({
sliderType: "min-range",
change: function(){
var obj1 = $("#slider").data("roundSlider");
value = obj1.getValue();
$("#slide").html(value);
});
$.ajax({
type: 'POST',
url: "{{url_for('test')}}",
contentType: 'application/json;charset=UTF-8',
data: {'data':value}
});
});
</script>
</body>
</html>
SERVER SIDE:
def flask():
connection()
app = Flask(__name__, template_folder='Templates')
#app.route('/test/', methods=['GET', 'POST'])
def test():
if request.method == "POST":
value=request.json['data']
print(value)
return render_template('roundslider1.html')
if __name__ == "__main__":
app.run(host='192.168.42.1',port=2030, debug=True)
After reading some more documentations, i used the below code to send the variable from j Query to flask server.
CLIENT SIDE:
var value;
$("#slider").roundSlider({
sliderType: "min-range",
change: function(){
var obj1 = $("#slider").data("roundSlider");
value = obj1.getValue();
$.getJSON('/valueofslider', {
a:value
});
SERVER SIDE:
#app.route('/valueofslider')
def slide():
a = request.args.get('a')
print (a)
I am developing an application in which from a website project I give a call to web api method using ajax call javascript. When I run both projects locally it works fine, but when I do publish web api project on demo site the ajax call does not reach to the web api method.
My ajax call is as follows-
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
var url = 'http://abc.demo.in/c60/api/Patient/Create/';
$.ajax({
url: url,
data: getData(),
type: 'POST',
contentType: "application/json",
success: function (result) {
console.log(result);
alert("success")
},
error: function (result) {
alert('POST failed.');
}
});
function getData() {
var patient = new Object();
patient.Name = "Mugdha";
patient.Gender = "Female";
patient.Email = "mugdhaShenoy#yahoo.co.in";
patient.Mobile = "";
patient.BloodGroup = "AB+";
patient.MedicalHistory = "High BP, Cholosterol, Diebetis";
patient.Allergy = "Dust, wind";
patient.EmergencyContactName = "Riya Sahani";
patient.EmergencyContactNo = "9988990200";
patient.ProfileImage = "";
patient.FormNo = "92";
patient.BirthDate = new Date(1989, 09, 08).toISOString();
return patient;
}
</script>
</head>
<body>
</body>
</html>
When I try to reach the api domain(which is on different server) I have faced an error as -
XMLHttpRequest cannot load http://abc.demo.in/c60/api/Patient/Create/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49370' is therefore not allowed access.
Is there any solution for this? I have added CorsHandler.cs file in my webapi project.
I'm trying to scrape a web page, but getting some weird results in my browser's console (as seen below). Here's my code:
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Icefilms Searcher</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="script.js"></script>
<div id="container" style="width:1100px;position:relative;"></div>
</body>
</html>
script.js
$(document).ready(function(){
var currNum = 168000;
var maxNum = 168005;
function generateNextUrl(){
currNum++;
return currNum-1;
}
scrapeThis(generateNextUrl());
function scrapeThis(theUrl){
$.ajax({
url:
"php.php",
data:
"icefilmsURL=" + theUrl,
success:
function(response){
var movieTitle = $(response).find("#videotitle").find("span:first").text();
$("#container").append("<a href='http://www.icefilms.info/ip.php?v="+theUrl+"' target='blank'>"+movieTitle+"</a><br>");
},
complete:
function(){
if(currNum < maxNum+1){
scrapeThis(generateNextUrl());
}
},
error:
function(xhr,err){
$("#container").append("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
$("#container").append("responseText: "+xhr.responseText);
}
});
};
});
php.php
<?php
echo file_get_contents("http://www.icefilms.info/ip.php?v=".$_GET["icefilmsURL"]);
?>
The code works fine, but this is what I see in my console:
Any ideas?
You are seeing those in the console because the page you are scraping contains references to relative paths.
That is to say rather than
<img src="http://www.icefilms.info/someimage.jpg">
The code is
<img src="someimage.jpg">
Therefore, when you grab and display their HTML on your own domain the browser is trying to load the image from your domain, localhost in this case. But you do not have the image on your server.
You can use a base href in the HTML to resolve this, or you could find and replace relative path images to include the domain.
<base href="http://www.icefilms.info/">