I have uploaded an image on a server powered by Golang. I want to show the same image in a HTML / JS page using XMLHttpRequest (XHR).
I'm having following challenges -
The static file server
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
is local to Go system and its template system. The Javascript doesn't know this system and can't find the required file.
So, while the img in HTML works (img src="/public/300x300.gif") works, this -
xhr.open("GET", "/public/300x300.gif", true);
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.send();
is not working.
How can I load an image on the page using AJAX while the file is available in Golang's virtual file system?
Related
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.)
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.
I use jquery jtable send ajax to get excel file from server but Response::download doesn't work
$writer = (new WriterFactory())->createWriter(new Excel5(public_path().'/file/myExport.xls'));
$phpExcel = $writer->convert($workbook);
$writer->write($phpExcel);
Response::download(public_path().'\file\myExport.xls');
Javascript cannot access file system, you cannot use ajax to download files. Try using an iframe pointing to the file to download it.
<iframe id="downloadFrame" style="display:none"/>
When you need to download, use this script:
var iframe = document.getElementById("downloadFrame");
iframe.src = "yourpathtofile";
If you use jQuery, you can try:
$("#downloadFrame").attr("src","yourpathtofile");
Another solution is using window.open
window.open("pathtoyourfle");
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.
Here is my situation:
Im creating a widget that site admins can embed in their site and the data are stored in my server. So the script basically has to make an ajax request to a php file in my server to update the database. Right? Right :)
The ajax request works excellent when i run it in my local server but it does not work when the php file is on my ONLINE server.
This is the code im using:
var url = "http://www.mydomain.net/ajax_php.php";
var params = "com=ins&id=1&mail=mymail#site.net";
http.async = true;
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//do my things here
alert( http.responseText );
}
}
http.send(params);
In firebug it shows: http://www.mydomain.net/ajax_php.php 200 OK X 600ms.
When i check the ajax responnseText I always get a Status:0
Now my question is: "Can i do cross-domain ajax requests by default? Might this be a cross-domain ajax problem? Since it works when the requested file resides in my local server but DOESN'T work when the requested file is in another server, im thinking ajax requests to another remote server might be denied? Can you help me clear on this?
Thanks..
Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:
function receiveData(data) {
// ...
}
And then your server wraps JSON data in a function call, like this:
receiveData({"the": "data"});
And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.
Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.
You're going to need to have your response sent back to your client via a JSONP call.
What you'll need to do is to have your request for data wrapped in a script tag. Your server will respond with your data wrapped in a function call. By downloading the script as an external resource, your browser will execute the script (just like adding a reference to an external JS file like jQuery) and pass the data to a known JS method. Your JS method will then take the data and do whatever you need to do with it.
Lots of steps involved. Using a library like jQuery provides a lot of support for this.
Hope this helps.