Can't Load Google Chart Using Json File with JSP - json

Im using Google charts API to load a pie chart from json file data
Here is where the chart is created (The HTML File) :
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "read.jsp",
dataType: "json"
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" ></div>aa
</body>
</html>
And here is the Read.jsp Used in url (ajax) :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.io.*, java.net.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Reading Text File</title>
</head>
<body>
<%
String fileName = "/WEB-INF/json/test.json";
InputStream ins = application.getResourceAsStream(fileName);
try
{
if(ins == null)
{
response.setStatus(response.SC_NOT_FOUND);
}
else
{
BufferedReader br = new BufferedReader((new InputStreamReader(ins)));
String data;
while((data= br.readLine())!= null)
{
out.println(data+"<br>");
}
}
}
catch(IOException e)
{
out.println(e.getMessage());
}
%>
</body>
</html>
And as a result I get this Error "Table has no columns" :
enter image description here
Anyone Know why please ? and thank you

by default, $.ajax is asynchronous,
need to wait on the done callback...
see following snippet...
function drawChart() {
$.ajax({
url: "read.jsp",
dataType: "json"
}).done(function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
});
}
EDIT
also, remove all the html from the jsp file,
this should be all you need...
<%# page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8" import="java.io.*, java.net.*"%>
<%
String fileName = "/WEB-INF/json/test.json";
InputStream ins = application.getResourceAsStream(fileName);
try
{
if(ins == null)
{
response.setStatus(response.SC_NOT_FOUND);
}
else
{
BufferedReader br = new BufferedReader((new InputStreamReader(ins)));
String data;
while((data= br.readLine())!= null)
{
out.println(data);
}
}
}
catch(IOException e)
{
out.println(e.getMessage());
}
%>

Related

asp.net ajax upload file always get null

I am trying to upload a file using jquery ajax, I can see the file object, its name, its size, etc.
In console by formdata.get("files"), but the context.request.files size is always zero, it seems the server does not receive the file from client, the HttpPostedFileBase request is always null.
How to fix it?
HTML:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="UploadKpData.aspx.cs" Inherits="WebApp.Admin.UploadKpData" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="./../Scripts/jquery-1.4.4.min.js"></script>
</head>
<body>
<div>
<div>
<input type="file" id="kpData"/>
<button type="submit" id="uploadKp" />
</div>
</div>
</body>
<script>
$("#uploadKp").click(function () {
var formdata = new FormData();
var files = $("#kpData").get(0).files[0];
formdata.append("files", files);
$.ajax({
url: "../../ds/UploadExcel.ashx",
type: "POST",
async: false,
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formdata,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
})
</script>
</html>
UploadExcel.ashx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApp.ds
{
public class UploadExcel : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpFileCollection file = context.Request.Files;
HttpPostedFile file1 = file[0];
string fileName = context.Server.MapPath("~/tmp/" + "test2.xlsx");
file1.SaveAs(fileName);
context.Response.ContentType = "text/plain";
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I have checked your code and all are working for me.
Let me share some screenshots :
Handler get file:
Project structure:
HTML page:

Authenticating with Facebook Graph API & Parsing JSON Reviews from a Facebook Page

I am having trouble authenticating and parsing.
get Facebook Graph api page review
I have tried to submit the app for review and request manage_page access but I get an error:
"Invalid Scopes: manage_pages. This message is only shown to developers. Users of your app will ignore these permissions if present. Please read the documentation for valid permissions at: developers.facebook.com/docs/facebook-login/permissions" and possibly the API is deprecated
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div id="results">
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
var myurl = "http://graph.facebook.com/v3.3/FinancialSanityNow/ratings";
var getToken = function(req, res) {
var facebookToken = req.headers['facebooktoken'];
//TODO : check the expirationdate of facebooktoken
if(facebookToken) {
var path = 'https://graph.facebook.com/v3.3/FinancialSanityNow?access_token=' + facebookToken;
request(path, function (error, response, body) {
var facebookUserData = JSON.parse(body);
if (!error && response && response.statusCode && response.statusCode == 200) {
if(facebookUserData && facebookUserData.id) {
var accessToken = jsonWebToken.sign(facebookUserData, jwtSecret, {
//Set the expiration
expiresIn: 86400
});
res.status(200).send(accessToken);
} else {
res.status(403);
res.send('Access Forbidden');
}
}
else {
console.log(facebookUserData.error);
//console.log(response);
res.status(500);
res.send('Access Forbidden');
}
});
res.status(403);
res.send('Access Forbidden');
}
};
$.ajax({
url: myurl,
headers: {
'access_token':'xxxxxaccesstokenherexxxxx',
},
method: 'GET',
dataType: 'json',
success: function(data){
$.each(data.reviews, function(i, item) {
// Store each review object in a variable
var reviewdata = item.data.reviews;
// Append our result into our page
$('#results').append('test:' + reviewdata);
});
}
});
</script>
</body>
</html>
I just want to know if this is even possible through pages/ratings api from facebook
https://developers.facebook.com/docs/graph-api/reference/page/ratings/
Most permissions need review before you can use them. Without review, they will only work for users with a role in the App, and you need to keep the App in dev mode. If you put it live, unapproved permissions will not work at all.
Also, you have to use a Page Token of the Page in question to get reviews, you get a Page token by using the /me/accounts?fields=access_token endpoint, with a User Token that includes the manage_pages permission.
More information about Tokens: https://developers.facebook.com/docs/facebook-login/access-tokens/

AngularJS databinding through responsemessage not working as expected

Code is as follows
var myApp = angular.module("gameModule", []);
myApp.controller("gamecontroller", function ($scope) {
$scope.message = "test";
// websocket connection.
var gameHub = $.connection.socketHub;
$.connection.hub.start().done(function () {
var clientid = $.connection.hub.id;
$(function () {
var user = { signalrsessionid: clientid };
$.ajax({
type: "POST",
data: JSON.stringify(user),
url: "http://localhost:53629/api/game/signalr",
contentType: "application/json"
}).done(function (response) {
alert(response);
$scope.responsemessage = response;
});
});
});
});
and front end code
<!DOCTYPE html>
<html ng-app="gameModule">
<head>
<title>game registration</title>
<meta charset="utf-8" />
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/jquery.signalR-2.2.1.js"></script>
<script src="Scripts/angular.js"></script>
<!--Automatisch gegenereerde signalR hub script -->
<script src="signalr/hubs"></script>
<script src="Scripts/rouletteAngular.js"></script>
</head>
<body>
<div ng-controller="gamecontroller">
{{ message }}
{{ responsemessage }}
</div>
So the 'message' is being displayed, the alert box with the response is showing the correct response, but the responsemessage doesnt show any value.
Can anyone tell me what i'm doing wrong.
you must call $scope.$apply(); or $scope.$digest(); after setting $scope.responsemessage = response; because you are using jQuery ajax call, which is outside Angulars context.
EDIT:
here you have nice way to use SignalR in AngularJS:
http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html

Load json data into the factory file

I am new to AngularJS and just started learning it. How can I load the JSON file into the script.js file without directly adding the entire data.
Here is the code of the program:
<!DOCTYPE html>
<html ng-app="quizApp">
<head>
<meta charset="utf-8" />
<title>QuizApp</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="container">
<h1 class="title">QuizApp</h1>
<quiz/>
</div>
</body>
Plunkr.
You need to correct the json pasted in ques.json (by using quotes "") otherwise if you will invoke $http.get() then you will get exception due to invalid json.
Once you will correct the json content in ques.json then just use $http and assign the result to questions variable.
E.g.
app.factory('quizFactory', function($http) {
var questions = [];
$http.get('ques.json').success(function(data) {
questions = data;
})
return {
getQuestion: function(id) {
if(id < questions.length) {
return questions[id];
} else {
return false;
}
}
};
});
Here is the demo
$http.get('ques.json')
.then(function(result){
$scope.questions = result.data;
});

How to Get Data from remote Webservice using jquery

I have problem in binding data to a control in html page,here we have a web service in remote location as we are binding the data to a control(dropdown) in html the data is not binding the code for fine for localhost but for the remote url.here i'm placing code below can any one tell me any modifications or any code to be added to it.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
</head>
<body>
<select id="CbxArea" style="width: 200px">
<option>Select Area</option>
</select>
<script type="text/javascript">
$(document).ready(function () {
//debugger;
var requestUrl = 'http://192.168.3.252:8081/HaraveerWCF/ExcelDataService.asmx/GetAreaNames';
var ddlArea = $("#CbxArea");
$.ajax({
url: "http://192.168.3.252:8081/HaraveerWCF/ExcelDataService.asmx/GetAreaNames",
//url: "ExcelDataService.asmx/GetAreaNames",
type: "POST",
dataType: "json",
contentType: "application/json; encoding=utf-8",
success: function (data) {
debugger;
for (i = 0; i < data.d.length; i++) {
ddlArea.append($("<option></option>").val(data.d[i].AreaName).html(data.d[i].AreaName));
};
alert(data.d.AreaName);
},
error: function (e) {
$('#status').innerHTML = "Unavailable";
}
});
});
</script>
Thanks in Advance.