Request.JSON run with page load - json

http://mootools.net/demos/?demo=Request.JSON
The JSON data load when you click on load JSON Data .
Is it possible to load this data when a page open ( a function like onload )

<head>
<script type="text/javascript">
window.addEvent("domready",function(){
var request = new Request.JSON({
url: '/echo/json/',
onRequest: function(){
gallery.set('text', 'Loading...');
},
onComplete: function(jsonObj) {
gallery.empty();
addImages(jsonObj.previews);
},
data: { // our demo runner and jsfiddle will return this exact data as a JSON string
json: JSON.encode(data)
}
}).send();
});
</script>
</head>

Related

passing json to kendoui grid

I would really appreciate guidance.
My script will make a call to my server, grab some data and bring it back as JSON. Then I call ServiceSucceeded(msg); I pass in the JSON results in msg. Now in ServiceSucceeded I want to display my results on kendoui grid. That is the part that I can't get to work. It gives no browser errors.
This code might be awful, so please school me on this , thanks!
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="../../assets/telerik/styles/kendo.common.min.css" />
<link rel="stylesheet" href="../../assets/telerik/styles/kendo.default.min.css" />
<script src="../../assets/telerik/js/jquery.min.js"></script>
<script src="../../assets/telerik/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid">
</div>
<div>
<script>
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var Username;
var Password;
var qryVar;
var locationName;
function GetAllReportDB() {
var dataId = "1";
Type = "GET";
qryVar = "userName=Simon"
Url = "http://localhost/UserReportMap.svc/GetAllReportDB?" + qryVar;
Data = '{"Contains": "Kir","DBName":"Bony","Operator":"BON0D"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; ProcessData = true;
Username = "test";
Password = "test";
CallService();
}
function CallService() {
$.support.cors = true;
$.ajax({
cache: false,
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
beforeSend: function (xhr2) {
xhr2.setRequestHeader("Authorization", "Basic " + window.btoa(Username + ':' + Password));
},
success: function (msg) {
ServiceSucceeded(msg);
alert("Succeeded");
},
error: function (errMsg) {
alert("Fail!");
}
});
}
function ServiceSucceeded(msg) {
var myResults = { "d": [{msg}] };
alert(JSON.stringify(msg));
$(function () {
$("#grid").kendoGrid({
dataType: "json",
schem: {
data: "d"
}
//columns: [{ title: "First Name" },
// { title: "Last Name" }]
});
});
}
$(document).ready(
function () {
GetAllReportDB();
}
);
</script>
</div>
</body>
</html>
Well, you have one typo at schem. It should be schema and not schem.
Anyway, I recommend check API docs, there is written what you need.
And to your question:
You are missing dataSource in your grid so it doesn't know from what data grid should be rendered.
$("#grid").kendoGrid({
dataSource: {
type: "json",
data: jsonData,
pageSize: 20
},
...
});
So line var myResults = { "d": [{msg}] }; can be removed and msg data can be assigned into dataSource. Then you will be able to set columns - here demo
And also consider, if you need load your json data in function and result assign into variable. Grid is able to load data from server without that - server just has to return json data, like in this example

Parse json and replace html

After submitting a form I'm directed to a blank page that shows some json data such as:
some error
{"status":0,"message":"some error message here"}
or success
{"status":1,"message":"You have been signed up!"}
I would like the contents of a span element to be replaced with the message from the json data.
span element:
<span class="ladda-label" id="notice">Get notified!</span>
My script is located after my jquery and is as follows
<script>
$(document).ready(function() {
$.ajax({
dataType: 'json',
success: function( data ) {
var prices = data.message;
$('#notice').html(data.message);
}
});
});
</script>
I'm pretty confident I'm not doing a single thing correctly here.
...be more carefull )
<script>
$.ajax('/my-data-url',{
dataType: 'json',
success: function( data ) {
var prices = data.message;
//$('#notice').text -> html( message.data !!! -> data.message);
$('#notice').html(data.message);
},
error: function() {
console.log('connection error')
}
});
</script>

Need Help Reading JSON object from a URL in a HTML

I am trying to create a website in where I can get a particular json object from a url and then display it on the website. The field that I am trying to display is UV_INDEX out of three fields. Nothing is being printed out. I don't even know if it is getting the json object.
<!DOCTYPE html>
<html>
<body>
<h2>EPA </h2>
<p id="demo"></p>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON').then(function(data) {
document.getElementById('UV_INDEX').innerHtml=json.result;
alert('Your Json result is: ' + json.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
</script>
</body>
</html>
I added a third-party chrome extenstion for CORS issue. But I get this error
Uncaught (in promise) ReferenceError: json is not definedmessage: "json is not defined"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
You can try using a Ajax plugin to make CORS request where the CORS headers are not being served from service.
Add Jquery library and add your installed CORS ajax scripts after that:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/jquery.ajax-cross-origin.min.js"></script>
Now you can make cross origin request by just adding crossOrigin: true in your Ajax:
E.g.
$.ajax({
crossOrigin: true,
url: "http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON/",
success: function(data) {
console.log(data);
}
});
You can try putting the same URL in the below demo page to receive the Json data.
See live demo.

Javascript to render charts not working with .getJSON

Correction: /devicedata to /products - that was a typo..
I have built a node-express app which I am using to to plot a graph from the data retrieved from mongo database. I have tried two external libraries Chart.js and Canvas.js. Both work perfectly fine when the data is hard-coded in the javascript. The moment I use $.getJSON to retrieve the data from database it stops working. On the server side code is as below:
app.get('/products', function(req, res) {
var db = req.db;
db.collection('products').find().toArray(function (err, items) {
res.json(items);
});
});
On the client side code is as below:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/products", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "Temperatures recorded this year"
},
data: [
{
type: "column",
dataPoints: result,
}
]
});
chart.render();
});
});
</script>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
Is there an alternative to .getJSON to retrieve data from database (mongo in this case) ? The chart is rendering as a blank canvas

One dimensional array of strings being parsed to 2d by angular resource

The following JSON response from the server
[
"hello",
"world"
]
is being parsed into a 2d array by this ngResource service
myService.factory('Name', function($resource){
return $resource(site_url+'api/accounts/:accountId/names/', {}, {
list: {method:'GET', params:{}, isArray:true}
});
});
called like so
$scope.names = Name.list({accountId:$scope.account.id}, function(e){
console.log(e);
});
traces to
[{"0":"h","1":"e","2":"l","3":"l","4":"o"},{"0":"w","1":"o","2":"r","3":"l","4":"d"}]
Any hints?
TLDR; ngResource expects an object or an array of objects in your response.
When isArray is set to true in the list of actions, the ngResource module iterates over each item received in the response and it creates a new instance of a Resource. To do this Angular performs a deep copy between the item received and the Resource class, which gives us an object with special methods ($save, $delete and so on)
Check the source here.
Internally angular uses angular.copy to perform the deep copy and this function only operates with objects and arrays, when we pass a string, it will treat it like an object.
Strings in JS can behave as arrays by providing sequential access to each character. angular.copy will produce the following when passed a string
angular.copy('hi',{}) => {0:'h', 1:'i'}
Each character becomes a value in an object, with its index set as the key. ngResource will provide a resource with properties 0 and 1.
Your choices are:
Use the lower level $http service
$http.get('/res').success(function(data){
$scope.test = data;
});
Return an array of objects in your json response
[{'data': "hello"}, {'data': "world"}]
Intercept the response and change your data
If you cannot modify the data the server sends back and want to use ngResource you will need to transform the response. Read how to do it here
I have been struggling with this as well. Here is my solution by adjusting the service slighly by using query
var app = angular.module('testApp', ['ngResource']);
app.factory('Name', function($resource, $sce) {
var path = "test.json";
return $resource(path, {}, {
query: {
method: 'GET',
isArray: false
}
})
});
app.controller('testController', function($scope, Name) {
$scope.result;
$scope.getResult = function() {
Name.query(function(data) {
$scope.result = data;
});
};
$scope.getResult();
});
HTML:
<!DOCTYPE html>
<html ng-app="testApp">
<head>
<link href="style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="testController">
<h1>{{result.surname}}</h1>
</body>
</html>
and the JSON file:
{
"name": "Homer",
"surname": "Simpson",
"Town": "Springfield"
}
and also working Plunker if interested: http://plnkr.co/edit/SwqlZyqZ4zfcpaLxaf39
Hope this help someone ...