I have a .php file running that is generating a downloadable file; when the .php file runs it opens a tab in the browser. Occasionally the .php file takes up to 15 seconds depending on the conditions to create the file.
I would like to know when this tab is open generating the downloadable file and when it closes. This way I can have some sort of loading message displayed while the file is being generated. When the .php file is done creating the file it automatically closes the tab.
Code:
var win = window.open(download, '_blank'); //opens the php file which generates the file.
if (win)
{
win.focus();
//have some sort of message stating to wait for the file to download here and then close it when the php file finishes running.
}
else
{
alert("Please allow popups.");
}
closePopup2();
I would suggest not opening a PHP file in a new tab, but using XMLHttpRequest(), you can find a guide on how to use it on MDN
You can use it like this:
function reqListener () {
console.log(this.responseText); // Will log full output of page
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", download);
oReq.send();
Give your window a unique id so the script will know which one to check (maybe needs to be random if opened/closed multiple times). I don't know if you need to focus, and popup permission is for you to figure out, but I think following should work:
var win = window.open(download, 'windowID', 'width:300px;height:300px');
win.document.write("<p>One moment please!</p>");
win.focus();
var test = setInterval(function() {
if(win.closed) {
clearInterval(test);
// do you stuff here after window closed
}
}, 500);
Related
Let say I have a database with several products. I'm making a page to create printable export of that database. On the page the user can setup the export depending on his needs. For example, choosing what categories of products he want to exclude from it, how he want it to be sorted and so on.
He then click on a button making an ajax call with the chosen settings to a php script making the sql request and everything.
From there I would like to generate a temporary html page to visualize the result and open it in a new tab to be printed. But once it is done, I don't need it anymore. I could write the html file from my php script and make my ajax call to open the new file on another tab but that would create a new file everytime and take a lot of space.
What is the best way to achieve that ? The main problem is that my php script result in a very long string that can't be send in the url. tmpfile() don't allow me to open the created file in a new tab as it is deleted at the end of the script.
I tried using tempnam() like this :
$tmpfname = tempnam("../tmp/",$_SESSION['loggedUser']);
$handle = fopen($tmpfname, "w");
fwrite($handle, "long string being my html code");
fclose($handle);
$success = true;
$return_arr = array($success,$tmpfname);
And my ajax call :
$.post('../php/export_script.php',{:settings},function(data){
response = JSON.parse(data);
if (response[0] == true) {
var win = window.open('../landing.php?file='+response[1], '_blank');
if (win) {
win.focus();
} else {
alert("Browser blocked the opening of the file.");
}
}else{
alert(response[1]);
}
});
So that open the landing.php page that is like so :
<div id="content">
<?php
$handle = $_GET['handle'];
$fileData = #file_get_contents($handle);
echo $fileData
?>
</div>
But that open the new tab with the clear path of the file in the url like this
"https://mywebsite.com/landing.php?file=/home/myserver/myproject/tmp/userV4rIkE"
That looks unsafe to me, showing some clear server infos to the user. Is there a better way to achieve this ? I though about just creating a normal file in my tmp folder generating a random name with timestamp + user session code and setting up a way for my server to empty that folder every once in a while.
In the parent page, you can use javascript to create a new page, which gives you a way to write data into that new page - so just write the HTML from the parent into the new page. It does not need any URL at all (about:blank) should work fine.
const handle = window.open();
if (handle) {
// write HTML to child.
}
after get request arrive the values are there and the button disappear
this is the button working on the localhost..
Im trying to add a Facebook share button in a page with dynamic contents like userid, coming from a esp826 server, using java script like innerhtml by ajax call get request once of json when the page body is on-load. When i test in my local host everything is ok since the json file load very fast and before the button loads and so everything works ok. but when i use the esp8266 server the response of the get request come somewhat after the button is loaded and so when it received and the fields get populated with the values the button disappear and remain only a word with a link.
basically the button is working on my localhost... so the innerhtml and everything is ok.. it seems i need to find a way to reload the css or something by the javascript to get the button box alive again.
is there a way to reload the button?
the .json file is just this: getajx.json
{"temp1":"1", "energia":"2", "energiatotal":"3", "tem":"2", "cliente":"22", "usuario":"22"}
you can test on your localhost by placing this getajx.json file having that content in the same directory of the html page is going to work... but i need to know how to make it work if the get request get too long.. please any help???
i tried to add a flag after the response is positive and activate the reloadCss funtion with it but didnt worked
<script>
var temp1, energia, energiatotal, tem, cliente, usuario ;
var ok=0;
function GetAjx() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
ok = 1;
var myObj = JSON.parse(this.responseText);
document.getElementById("temp1").innerHTML = myObj.temp1;
document.getElementById("energiatotal").innerHTML = myObj.energiatotal;
document.getElementById("tem").innerHTML = myObj.tem;
}};
if (ok =1) { function reloadCss(){
var links = document.getElementsByTagName("link");
for (var cl in links){
var link = links[cl];
if (link.rel === "stylesheet")
link.href += "";
}}
};
xmlhttp.open("GET", "getajx.json" , true);
xmlhttp.send();
}
</script>
I found a solution...
apparently i had to change the order of the scripts making the jquery ajax source load first and also tried to put the script from facebook at the bottom of the page...
i took away the reload scripts and other facebook scripts i was testing
and most importantly made the get request false to make it sync instead of async this forces the page to wait for the get request finish..strangely i tried it before and didnt worked this solution perhaps because of the order of the scripts.. can anyone comment on that?
xmlhttp.open("GET", "getajx.json" , false);
was helpful using the f12 on google chrome in specific the performance tab
i decided to not mess up with priority of the scripts even if i tried
any comments i would appreciate
again
thanks for the help
I'm currently working through the book "Head first HTML5 programming". I want to load the content of a file named sales.json from a web server on my own machine. I used wampserver for this.
In the folder wamp/www/gumball/ I put all relevant .html, .js and .css files, and also the sales.json file.
My JavaScript code is very simple:
window.onload = function() {
var url = "http://localhost/gumball/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
This doesn't do anything! Typing the link: http://localhost/gumball/sales.json in my browser opens the right file, so the link should be correct. Even when using the .js files that come with the book (with a finished version of the application I'm trying to make), nothing loads.
Testing with alert statements tells me the request.onload event never happens. I'm clueless as to why this is the case.
A fact I don't quite understand yet: when I type: http://localhost/gumball/sales.json: in my browser (I added a colon at the end of the link), I get a 403 Forbidden error! Why does this happen? Does this have something to do with my problem?
I open html document with firefox
Your HTML document must be open with a URL in http://, not file://, if you want it to be able to open in javascript another document, unless the second document is served with relevant CORS headers.
This is due to same origin policy.
As you have a local WAMP server, there is no problem : simply open your file using a http:// URL like you do for your JSON file.
I am trying to load the same link of the tab into the popup window (this is not my primary purpose and i am doing this just to get acquainted) I am getting the error
Failed to load resource: net::ERR_FILE_NOT_FOUND
My js file is as follows
var pageGenerator = {
requestPage: function() {
var urlTosearch;
chrome.windows.getCurrent(function(w) {
chrome.tabs.getSelected(w.id,
function (response){
urlTosearch = response.url;
});
});
var req = new XMLHttpRequest();
req.open("GET", urlTosearch, true);
req.onload = this.loadPage_.bind(this);
req.send(null);
},
loadPage_: function (e) {
var resp = e.target.responseText;
document.body.insertAdjacentHTML( 'beforeend', resp);
}
};
document.addEventListener('DOMContentLoaded', function () {
pageGenerator.requestPage();
});
I have read that external pages can not be loaded onto the popup. Is it so? If true why? and if not how can it be done?
When receiving Failed to load resource: net::ERR_FILE_NOT_FOUND you probably didn't defined your url correctly. Since i don't see your url in your piece of code and i see no accepted answer i will share what i think goes wrong.
At first you have to define the url you are posting in your manifest with:
"permissions": [
"http://www.yoururl.com/"
],
Also when calling your api by: yoururl.com/ the chrome extension will not call the api. Just simply because it thinks the url is withing the scope of your extension locally. To solve this you have to define http://www. or https://www. Now Chrome will recognize you try to load something from outside of the extension.
Try using the Active Tab permission FROM A BACKGROUND script in order the get the URL of the current page. Then use chrome.tabs.create() to open a new tab with that same URL.
Details here: https://developer.chrome.com/extensions/activeTab
I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.