Need Help Reading JSON object from a URL in a HTML - 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.

Related

POST-request with multipart/form-data from ExtJS form to .Net5 controller gets responseText empty

I have a form in ExtJS:
{
xtype: 'form',
items: [{
xtype: 'filefield',
name: 'azezFile'
}],
buttons: [{
text: 'Load',
handler: function() {
var form = this.up('form').getForm();
if(form.isValid()) {
form.submit({
url: uploadApiPath,
success: function(fp, o) {
// Never goes here
}
});
...
It sends file to a controller (.Net5):
namespace KROSS_Core.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class UploadController : ControllerBase
{
// POST: api/Upload
[HttpPost]
public IActionResult Post([FromForm] IFormFile file)
{
//AzezUploadFile(this.HttpContext);
return Ok(new { success = true });
//return Ok(LoadFileToBase(this.HttpContext));
//return BadRequest(new { success = false, message = "Wrong answer" });
}
Controller getting request and responses normally, but I got an exception in ext-all-debug.js:
Unhandled exception at line 6092, column 17 in
https : // localhost:44364/Website/Scripts/ext.js/ext-all-debug.js
0x800a139e - Error JavaScript: Ext.JSON.decode(): You're trying to
decode an invalid JSON String:
And response.responseText is empty in debugger. After I close that exception, the browser (IE11) asks me to save or open that json file.
Firefox shows another error in console:
"You're trying to decode an invalid JSON String: <pre>{\"success\":true}</pre>"
, but it was set [Produces("application/json")] in controller...
Google Chrome log: "You're trying to decode an invalid JSON String: <pre style="word-wrap: break-word; white-space: pre-wrap;">{"success":true}</pre>"
What is the problem and how to make it working? The same controller method loaded without sending multipart form-data goes normally and ExtJS works with response JSON.
I have no idea how to fix it in ExtJS, but I used another method of uploading a file to a server (same controller), and it works perfect:
function uploadFile(file, url, success, failure) {
var formData = new FormData();
var request = new XMLHttpRequest();
formData.append('file', file);
request.onload = function (response) {
var jsonResult = JSON.parse(response.target.responseText);
if (jsonResult.exception || jsonResult.error) {
failure(jsonResult);
}
else {
success(jsonResult);
}
};
request.open("POST", url);
request.send(formData);
}
And use it like
uploadFile(form.down('[name=fileInnputName]').extractFileInput().files[0], uploadApiPath, function() { }, function() { });

Constant POST request to different server from HTML

I want to create a HTML page which offers a button (link, some other clickable element, etc.) which, when pressed, sends a specific constant POST request to a specific constant server. The value I need to post is a specific constant JSON-encoded value ({"key":"value"}), so for HTTP it is just a very short constant string.
The value and the URL I have to use are constant. In order to make something happen, I have to send exactly this constant POST request. There is no need to parameterize this request or to "set a value" or similar. Also, I have no parameter name or similar. I must not send a parameter list with a parameter whose value is the JSON-encoded value, but I must send the JSON-encoded value by itself. The complete POST request can look like this:
POST /post/path/to/action HTTP/1.1
Host: the.specific.server
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
{"key":"value"}
(NOT parameter={"key":"value"} or similar as body!)
The server is not under my authority but a service I want to use.
With pure shell means I can do this very simply using curl:
curl http://the.specific.server/post/path/to/action -d '{"key":"value"}'
I imagined something like
<button url="http://the.specific.server/post/path/to/action"
value="{%22key%22:%22value%22}">visible text</button>
but I found nothing appropriate.
Based on questions like this or this or this I tried various approaches like this one:
<form method="POST" action="http://the.specific.server/post/path/to/action">
<input type="text" id="key" key="value">value</input>
<button type="submit" value="{%22key%22:%22value%22}">visible text</button>
</form>
With or without the input field, the button, with other arguments, other values, etc. but nothing finally sent anything useful to the server when pressed. At best I got something which was also transmitting a parameter name (thus the payload was not just the Json-encoded value).
I guess I'm just missing something basic in this :-}
There is no way in HTML to generate JSON from forms. You need here to implement this using an AJAX request.
Using jQuery it could be something like that:
$.ajax({
type: 'POST',
url: 'http://the.specific.server/post/path/to/action',
data: '{"key":"value"}',
success: function() {
// Successful response received here
},
dataType: 'json',
contentType : 'application/json'
});
This will be trigger when clicking on a button or a link, as described below:
$('#myButtonId').click(function() {
$.ajax({
(...)
});
});
This can be put for example in a script in your page after including jQuery library, as described below:
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
// Waiting for the DOM to be loaded
$(document).ready(function() {
$('#myButtonId').click(function() {
// When button is clicked
$.ajax({
(...)
});
});
});
</script>
<body>
<button id="myButtonId">CLICK ME</button>
</body>
</head>
Edited
Here is the way to send an HTTP request using raw JavaScript API: http://www.quirksmode.org/js/xmlhttp.html.
I adapted this code to work for your use case:
function sendRequest(url, callback, postData, contentType) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData) {
if (contentType) {
req.setRequestHeader('Content-type', contentType);
} else {
req.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
}
}
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
} catch (e) {
continue;
}
break;
}
return xmlhttp;
}
To execute your request, simply use the function sendRequest:
sendRequest(
'http://the.specific.server/post/path/to/action',
function() {
// called when the response is received from server
},
'{"key":"value"}',
'application/json');
Hope it helps you,
Thierry
A simple, customisable an no dependencies solution based on : https://gist.github.com/Xeoncross/7663273
May works on IE 5.5+, Firefox, Opera, Chrome, Safari.
<html>
<body>
<button id="myButtonId" onclick='post("http://the.specific.server/post/path/to/action", "{\"key\":\"value\"}");'>CLICK ME</button>
</body>
<script>
function post(url, data, callback) {
try {
var req = new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
req.open('POST', url, 1);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.send(data)
} catch (e) {
window.console && console.log(e);
}
}
</script>
</html>
You are looking for FORM encoding algorithm which enables form data to be transmitted as json.
Have a look at W3C HTML JSON form submission. It is not active and not likely to be maintained.
So, you are better off using the above JS or Jquery solution or use a server side forwarding. My suggestion is to use jquery as most websites point to google cdn these days and jquery is mostly browser cached. With below code, you neatly fire a POST request without worrying about underlying browser variants.
$.ajax({
type: 'POST',
url: 'http://the.specific.server/post/path/to/action',
data: '{"key":"value"}',
success: function() {
// Successful response received here
},
dataType: 'json',
contentType : 'application/json'
});
Try this suggestion using JQuery methods and Ajax:
$(document).ready(function(){
$("#myForm").submit(function(){
$.ajax({type:"POST",
data: $(this).serializeObject(),
url:"http://the.specific.server/post/path/to/action",
contentType: "application/json; charset=UTF-8",
success: function(data){
// ... OK
},
error: function(){
// ... An error occured
}
});
return false;
});
});
Note : serializeObject method converts form elements to a JSON string.
I now went for a simplistic solution (because that's what I wanted) I found myself by searching for more answers. It seems there is no way around using JS for this task.
<button onClick="postCommand('mypath', 'mykey', 'myvalue')">Click</button>
<script>
function postCommand(path, key, value) {
var client = new XMLHttpRequest();
var url = "http://the.specific.server/" + path;
client.open("POST", url, true);
client.send("{\"" + key + "\":\"" + value + "\"}");
}
</script>
This is in general #aprovent's answer, so I accepted his and granted him the bounty.

Setting up the Header Using Http to get the Json file

I do have a working table using JSON and angular, I set up my $http header to get the Json in the particular .api, I run it but nothings appear in getting my Json file in the $Http.get, I would like to ask if this is a valid header, I mean is there something wrong with my delimeter?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<script type="text/javascript">
var myTable=angular.module('myTable',[]);
myTable.controller('tableCtrl',function($scope,$http){
$http.get ("http://staging.api.sample.com/events.json", {header: {Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'}}); .success(function(response) {
debugger
$scope.members=response.events;
$scope.totals = response.paging;
});
});
Remember about correct style guide. It should help you. Also check this link https://github.com/johnpapa/angular-styleguide/
(function {
'use strict';
angular
.module('myTable', [])
.controller('tableCtrl', tableCtrl);
tableCtrl.$inject = ['$scope', '$http'];
function tableCtrl($scope, $http) {
$http.get("http://staging.api.sample.com/events.json", {
header: {
Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'
}
}).then(function(response.data) {
$scope.members = response.data.events;
$scope.totals = response.data.paging;
}).catch(function(error) {
});
});
}());
This query is wrong:
$http.get("http://staging.api.sample.com/events.json", {
header: {
Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'
}
}
You can pass parametes by get building query like this one:
$http.get("http://staging.api.sample.com/customer/1") or
$http.get("http://staging.api.sample.com/customer/" + some_param). If you would like to send some object to you API you should use POST. For example:
$http.post("http://staging.api.sample.com/events.json", {object});

How is possible to load some setting from .json file before angular app starts

i'm building application which uses CORS requests. Each request i use get host address from a constant
angular.module('siteApp').constant('baseUrl', {
'server':'htttp://localhost/',
})
And in each service i use to send request like this:
angular.module('siteApp').factory('DocsSvc', function ($http, baseUrl) {
var baseurl = baseUrl.server ;
$http.get(baseurl + 'document')
Is it possible to make 'htttp://localhost/' value - to came from config.json file into baseUrl constant or baseUrl factory?
I mean : how can i load something from ajax request an make it accessible to app modules
i have tried:
.run(['$rootScope', , function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
});
And tried to access it from baseUrl:
angular.module('siteApp').factory('baseUrl',function($rootScope) {
return {
server: $rootScope.HOST
But no luck - the baseUrl.server comes undefined into functions
You can use run method of angular.
var app = angular.module('plunker', []);
app.run(function($http, $rootScope){
$http.get('config.json')
.success(function(data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function(data, status, headers, config) {
// log error
alert('error');
});
})
app.controller('MainCtrl', function($scope, $rootScope) {
$scope.$on('config-loaded', function(){
$scope.name = $rootScope.config.name;
});
});
see this plunker
If you want to do it even before the angular app starts, you can, instead of using the ng-app directive, use the bootstrap function.
From:
https://docs.angularjs.org/api/ng/function/angular.bootstrap
<!doctype html>
<html>
<body>
<div ng-controller="WelcomeController">
{{greeting}}
</div>
<script src="angular.js"></script>
<script>
var app = angular.module('demo', [])
.controller('WelcomeController', function($scope) {
$scope.greeting = 'Welcome!';
});
// Do your loading of JSON here
angular.bootstrap(document, ['demo']);
</script>
</body>
</html>
You need to tell angular about data change, so modify your code something like this:
.run(['$rootScope', function ($rootScope) {
$.ajax('config.json', {async: false})
.success(function (data) {
$rootScope.HOST = data.HOST;
$rootScope.$apply(); // New line
});
}])
That $apply() is needed since its a non-angular asynchronous call.
use the blow code snippet to load the json values
.run(function ($http, $rootScope) {
$http.get('launchSettings.json')
.success(function (data, status, headers, config) {
$rootScope.config = data;
$rootScope.$broadcast('config-loaded');
})
.error(function (data, status, headers, config) {
// log error
alert('error');
});
});

Request.JSON run with page load

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>