Google Storage Ajax load Json File not working - ajax

I am using ajax in html to load Json files to that the data will be refreshed every 5 seconds.
When I test it on my local host, everything works great. However, when I upload to google cloud Storage, it gives me some error shown as
Failed to load resource: the server responded with a status of 404 ()
GET https://00e9e64bac97921ce699e88ff28fbd14910d2de64676b68d82-apidata.googleus…/storage/v1/b/../o/TableGenerationData.json 400 ()
I put the json file in the same folder with the html, and my code is sure working,
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script type="text/javascript">
function refreshData()
{
var tt = $.ajax({
url: "TableGenerationData.json",
dataType: "json",
async: false
});
var jsonData = tt.responseJSON;
}
</script>
I couldn't get it working in google storage, does anyone have any idea?
Thank you very much.

Finally figured it out.
To make it work, I need to open the public link of the html file, and set the json file to be 'no-cache' to make sure new uploaded data will be immediately fetched by the html.
Thank you very much, welcome to make comment and share your idea if I am wrong.

Related

Call express (node.js) APIs from static HTML page on host

I have a static HTML page, hello.html. If I double click hello.html, it opens up in my default browser, and displays the HTML properly, but in the browser's search bar, instead of having a URL with a hostname, what displays is the local filepath for hello.html on my computer.
I have made a simple express web server on my computer, using express (node.js). It is set to listen on port 8080, and has a simple GET api. (The API right now does something simple like call 'ls'). I wanted to be able to call that GET API, from my static hello.html. In my static HTML page, I use jquery to make an ajax call to this api, calling it as http://127.0.0.1:8080/myapi. Once I start the express server and load the page, looking at the console logs, the requests to myapi are going through when I load the static HTML page in the browser (the ls response is getting logged on the console), however, the jquery ajax in the HTML page, always executes the error function, even when I'm setting the response as 200.
I was reading a lot about why this happens, and read it could be due to CORS issue. However, there is no hostname I can specify on the server side, to allow in this case, since there is not actually a web server running, and so there is no actual host name associated with my static HTML page.
Is this even possible to do? (To have a static HTML page on your computer with no web server running, make your own express server with APIs, and call those APIs from the static web page?)
Example:
hello.html
<html>
<head>
<title>Hello World</title>
</head>
<body>
<script src"js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8080/myapi",
contentType: 'application/json',
success: function(response) {
alert("success!");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error");
},
});
});
</script>
<p>Hello World!</p>
</body>
</html>
myserver.js:
var express = require('express');
var shelljs = require('shelljs');
var app = express();
app.get('/myapi', function (req, res) {
shellStr = shelljs.exec('ls');
if ( shellStr ) {
console.log("successful call on server side");
res.status(200);
res.json({ ls: shellStr });
}
else {
console.log("failure status on server side");
res.status(500).json({ error: "Could not do ls"});
}
})
var server = app.listen(8080, function() {
console.log("Listening on 8080");
})
I am starting up the server by giving 'node myserver.js', and then I open the static HTML page in the browser. When it loads, the API call is being made, as I see the server side console output, and it's going as success. However, back in the static html, the ajax call's 'error' function is always executed.
I got it to work!
In case anyone else ever wonders, and is new to express and web servers like myself.
The key was to have express serve hello.html as well. It is simple to do this.
I had my express server in a directory like this:
myserver/myserver.js <-- this is my express server
I moved all of my static html files, in to a directory at the same level.
myserver/htmlfiles/ <-- this directory has 'hello.html'.
Now, in myserver.js, I added the following line near the top, just after var app = express():
app.use(express.static('myhtml'))
What this does, is it will tell express to serve any static files in the directory myhtml (will search for that directory, relative to where the myserver.js is.)
If I restart the express server (kill the current one then just run 'node myserver.js' again), and go to the browser, if I visit http://127.0.0.1:8080/hello.html - the page shows up!
Now the domain origin is the same, and when the ajax call is made to the api, it is successful in the browser, too!
(Note - I did have an issue at first after these changes, because my ajax URL in hello.html was calling http://localhost:8080/myapi, but I was displaying hello.html in the browser via http://127.0.0.1:8080/hello.html. Once I changed the ajax URL being called to http://127.0.0.1:8080/myapi - everything worked. Similarly, if I open the browser and go to http://localhost:8080/hello.html and display hello.html that way, if the ajax URL being called is http://127.0.0.1:8080/myapi - the ajax call will go in to the 'error' function. It seems that the hostname you are using in the ajax URL in the HTML page, must be the same (127.0.0.01 vs. localhost) as the hostname you are using to visit the html page in the browser when the call is made.)

Can I force refresh content/page using Spring Boot and JSP?

I am newbie at spring and generally webdev. I am writing small application in spring boot, where on hompage I display actual weatherstatus. Data is storage with help of JpaRepository and HSQLDB.
Each minute I recive data, parse, and add it to repository. The logic is done.
How to force client's browser to refresh, when I get new, actual Data?
With HTML:
To add this kind of feature without using any Ajax feature, you can use the following meta:
<meta http-equiv="refresh" content="0;URL='http://thetudors.example.com/'" />
https://www.w3.org/TR/WCAG20-TECHS/H76.html
With Javascript:
If you can add Javascript in the project, my advice is to create a endpoint to check periodically with JQuery or Fetch:
http://api.jquery.com/jquery.ajax/
https://www.npmjs.com/package/fetch
Juan Antonio
If you are using REST calls then it will be very easy for you.
<script>
$(document).ready(function(){
setInterval(getWeather(),2000);
//Here get weather is a method and 2000 is numbers of milliseconds after which you want to update weather data
});
function getWeather(){
$.ajax({
type : 'GET'
url : 'Your url here'
success : function(data){
//set received data to your container
}
});
}
</script>

ajax from same site as JS reference file?

I have a JS file running on my site, it works fine.
Now I want to put on another site with the full url of the script back to my site.
<script src="http://www-js.mydomains.com/some/path/file.js"></script>
now is it really still cross domain to an xml request on my server?
so in the file.js I have something like
dojo.xhrGet({url: '/some/path/file.xml', sync: true, handleAs: 'xml', error: function(result,args){alert(result.responseText+'-'+args.responseText)}, load: function(result){ ....
this just dies on other sites (great dojo response of undefined)... is there away around it
I think you should use "script" dojo/request/script instead of xhr.
require(["dojo/request/script", "dojo/dom", "dojo/dom-construct", "dojo/json", "dojo/on", "dojo/domReady!"],
function(script, dom, domConst, JSON, on){
on(dom.byId("startButton"), "click", function(){
domConst.place("<p>Requesting...</p>", "output");
script.get("helloworld.jsonp.js", {
jsonp: "callback"
}).then(function(data){
domConst.place("<p>response data: <code>" + JSON.stringify(data) + "</code></p>", "output");
});
});
});
http://dojotoolkit.org/reference-guide/1.9/dojo/request/script.html
now is it really still cross domain to an xml request on my server?
Yes. The origin is based on the URI of the HTML document hosting the script, not the URI the script was sourced from.
You should send the HTTP headers defined in the CORS specification to allow other sites to use your script (or their own scripts) to access content on your server.
Additionally, URIs accessed by JS are also relative to the document and not the script, so you will need to use an absolute or scheme relative URI instead of the server root relative URI you are presently using.

sending an HTTP request with an unordinary method

I am trying to create a link on my web page that when accessed will cause an HTTP request with an unordinary method to be sent (for the sake of the example, the method is POSTS).
I know that regular HTML forms support only GET and POST and AJAX should support PUT and delete. Is there a way to issue requests with a method different than these standard HTTP methods?
Thanks in advance.
==============
After the tips I adjusted my page to have the following HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"http://www.example.php",type:"POSTS",dataType:"html"});
});
});
</script>
</head>
<body>
<button>Send Request</button>
</body>
</html>
Surprisingly, this did not work in Chrome and Firefox but did work in an updated version of IE:
When I tried to issue the request using Firefox and Chrome, the browser issued a request with an OPTIONS method and the following header:
Access-Control-Request-Method: POSTS
Only IE issued the request as per the requirement - using the POSTS HTTP method.
===
Turns out that the aforementioned HTML doesn't work.(The desired request with the custom header is not issued).
As I mentioned above, firefox and chrome issue an initial request with an Access-Control-Request-Method header , while IE doesn't issue a request at all.
I adjusted the browser security settings (enabled "Access data sources across domains),
but still, the browser did not issue the request.
I'm guessing there needs to be some further adjustments in the browser setting, does anyone have an idea how this can be solved?
Quick answer yes if you use javascript.
Methods are defined by the standard along with status codes however they are open to extension. Such as webdav which increases the method vocabulary.
Not all browsers support arbitrary http methods especially older versions of IE (surprise surprise!)
So you could simply have a link / button which calls a javascript function which makes your http request.
Simply using jQuery:
var request = $.ajax({
url: "script.php",
type: "POSTS",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});

Get remote xml file by AJAX and parse it with jquery

I'm developing a HTML5 application for Blackberry OS 5+.
I'm using jQuery to download and XML file and show it using this function:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "http://xxx.com/yyy/mTop",
dataType: "xml",
success: function(xml) {
$(xml).find('item').each(function(){
var tipo = $(this).find('tipo').text();
var porcentaje = $(this).find('porcentaje').text();
$('<div class="items"></div>').html('<p>' + tipo + ' - ' + porcentaje + '</p>').appendTo('#page-wrap');
});
}
});
});
But I'm getting this error:
XMLHttpRequest cannot load http://xxx.com/yyy/mTop. Origin file:// is not allowed by Access-Control-Allow-Origin.
How can I parse a remote XML file?
Maybe I need to convert XML retrieved to a DOM object for use with jQuery.
That's because of Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites
you should use JSONP instead.
And the reason why you dont have a file location in your link ( url: "http ://xxx.com/yyy/mTop" ) is becouse the site "produces" an xml the moment you visit the folder, slowing down the website each time you reach it..
What you must do is:
go to http ://xxx.com/yyy/mTop on your browser
right click - view source code - copy to notepad - save as .xml
upload file to another folder
then change your code url to this url: "http ://xxx.com/yyy/mTop/yourdailyXMLcopy. xml
and keep updating the file daily..else you will kill the server querying each time any user uses your thing for a huge job...
Part of your problem is your file path is to a folder and not an XML file. Start there and see if you're problem still exists.

Resources