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

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>

Related

Angular JS - Error: $http:badreq Bad Request Configuration

I am learning Angular JS. I am trying to create a mock portal that displays Daily Messages. I have stored my daily messages in a database table.
create table DailyMsg(Sno int primary key, msg varchar(max));
Then I created a service using factory in AngularJS.
public class DailyMsgsController : Controller
{
private amenEntities1 db = new amenEntities1();
// GET: DailyMsgs
public ActionResult Index()
{
return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
}
}
I tested the URL and it works fine, it returns the expected data in the JSON format
https://localhost:44329/DailyMsgs
Now, I wanted to display this data on my HomePage. But it doesn't work. On inspecting the page it shows me the error
Error: $http:badreq
Bad Request Configuration
Http request configuration url must be a string or a $sce trusted object. Received: undefined
My Controller
var myApp = angular.module('myApp', []);
//Daily Messages Service Function
myApp.factory('DailyMsgService', function ($http) {
DailyMsgObj = {};
DailyMsgObj.DisplayDailyMsg = function () {
var Msg;
Msg = $http({method: 'GET', URL: '/DailyMsgs/Index'}).
then(function (response){
return response.data;
});
return Msg;
}
return DailyMsgObj;
});
myApp.controller('HomePageController', function ($scope, DailyMsgService) {
DailyMsgService.DisplayDailyMsg().then(function (result) {
$scope.DailyMsg = result;
});
});
My HomePage
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div ng-controller="HomePageController">
{{DailyMsg}}
</div>
</body>
</html>
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../AngularControllers/HomePageController.js"></script>

JS, how can i refresh the page or div when json data changed?

Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);

Getting chart.js to work with Django and Apache

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'

How to send a cross-domain POST request using ajax call in c#

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.

$(document).ready function won't fire up

I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events

Categories