I have a simple page with button which calls HttpHandler via JavaScript.
HttpHandler gets lots of files and adds them to a zip file, after finishing work zip file will be added to Response.
This operation can take several minutes. I would like to execute some JavaScript function after finishing work of HttpHandler.
How can I do it?
My code:
<asp:Button ID="btnDownload" runat=server Text="Download" OnClientClick="Download()" />
<script type="text/javascript">
function Download()
{
var url = 'FileStorage.ashx';
window.open(url);
}
</script>
UPD 1:
I have found other solution. Using XMLHttpRequest.
Code:
<script type="text/javascript">
var xmlHttpReq = createXMLHttpRequest();
function Download() {
var url = 'FileStorage.ashx';
xmlHttpReq.open("GET", url, false);
xmlHttpReq.onreadystatechange = onResponse;
xmlHttpReq.send(null);
}
function onResponse() {
if (xmlHttpReq.readyState != 4)
{ return; }
var serverResponse = xmlHttpReq.responseText;
alert(serverResponse);
}
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch (e) { }
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { }
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
alert("XMLHttpRequest not supported");
return null;
}
</script>
In onResponse() I can see my zip file in responseText (binary). But I don't have any idea how I can say to browser to download result of working httphandler such as file.
Any ideas?
I would use JQuery AJAX and then on success, write a function that will do whatever work you need it to. Plus with AJAX you can show the user an icon that says loading so they know something is actually processing, instead of the page just hanging and nothing appearing to happen.
$.ajax({
url: "FileStorage.ashx",
context: document.body,
success: function(){
// Whatever you want to do here in javascript.
}
});
Related
I have the following generic Ajax response writer which I recently added some logic to, in order to dynamically parse the results for script objects, and run them when I find them using jQuery.globalEval().
Here is the code:
//Generic Results Writter method for Ajax Calls
function writeAjaxResponse(targetId, response) {
document.getElementById(targetId).innerHTML = response;
try {
var dom = $j(response);
dom.find('script').each( function(){
$j.globalEval(this.text || this.textContent || this.innerHTML || '');
});
} catch (e) {
console.error("Error parsing for script reloads: "+e);
}
}
This solution works very nicely the first time its called. However writeAjaxResponse(targetId, response); is called each time a user loads some dynamic Ajax content. And unfortunately after the first time, the scripts are no longer loaded. To be clear, after the server side generated page is loaded, there are numerous links on the page which the users may click, which invoke this handler for the Ajax response.
No error occurs, and no console.error() is written.. The Ajax data loads as normal, its just that the scripts in the response are no longer loaded.
In debugging, $j.globalEval is still getting called and this.text still has the script content in it, and the data looks correct, but still no joy.
Any light someone could shed on this would be very much appreciated!
Adding main ajax call for GET for reference:
function doAjaxGet(targetId, getUrl, handler) {`
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
handler(targetId, xmlhttp.response);
}
catch (err) {
alert("Failed calling handler, detail: " + err + " Got responseText: " + xmlhttp.responseText);
}
}
}
xmlhttp.open("GET", getUrl, true);
xmlhttp.send(null);
}
Having this API:
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
How can I write using pure JS request that downloads me different data after button click event?
All I get from this code is the same quote all the time:
function getQuote (cb) {
var xmlhttp = new XMLHttpRequest();
var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && this.readyState==4) {
cb(this.responseText);
}
};
xmlhttp.open("GET", quoteURL, true);
xmlhttp.send();
}
document.querySelector('button').addEventListener("click", function() {
getQuote(function(quote) {
console.log(quote);
});
})
I tried xmlhttp.abort() and stuff but it didnt want to cooperate.
Thanks in advance!
Your response is being cached by the browser. A common trick to avoid this is to perform a request to
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}
Notice how the r={random_number} will make the URL different each time.
This is a caching problem. Add a timestamp as a query parameter and you should be able to bust the cache.
I'm trying to have a div refresh after a callback using ajax functions. Basically, I want /includes/view_game/achievements.inc.php to be reloaded in the div #achievements_tab. The callback (I didn't include it in codes below) works well and triggers the AchievementRefresh function found below (the opacity of the div changes to 0.5, but it remains like this and the refresh is not made).
Those two functions are used for another similar ajax refresh on my site that works well. So I tried to modify the code, but since it's for a slightly different purpose, maybe I have the wrong approach.
function AjaxPost(url, success_function) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser doesn't support AJAX. You should upgrade it!")
return
}
xmlHttp.onreadystatechange = success_function;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
This AjaxPost function is used in the other function below:
function AchievementRefresh() {
div('achievements_tab').style.opacity = 0.5;
div('highscore_pages').innerHTML = '<img src="'+site_url+'/images/loader.gif" />';
AjaxPost(site_url+"/includes/view_game/achievements.inc.php?", '',
function () {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
)
}
Use load
$('#achievements_tab').load('/includes/view_game/achievements.inc.php');
See: http://api.jquery.com/load/
Edit
E.g.
function AchievementRefresh() {
$('#achievements_tab').css('opacity', 0.5);
$('#highscore_pages').html('<img src="'+site_url+'/images/loader.gif" />');
$('#achievements_tab').load('/includes/view_game/achievements.inc.php')
.success(function() {
$('#achievements_tab').css('opacity', 1);
});
}
Try this.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
}
};`
Name and id is example.
Also, some changes:
AjaxPost(site_url+"/includes/view_game/achievements.inc.php");
var params= 'name'+encodeURIComponent(name)+'&id='+encodeURIComponent(id)
Parameters shouldn't be in URL.
xmlhttp.send(params);
Now, I have a problem with the ajax call which is when the web page is loaded, in the onload event of body, I assign it to call the functions which are startCount() and updateTable() this two functions contain the code that use ajax call to get the data from DB on the server side. The problem is when the ajax return it will return only one call and another call does not response. Please help me what happen and how I can slove it.
This is the onload in the body
<body onLoad="setAjaxConnection();startCount();updateTable()">
I use the XMLHttpRequest with the normal javascript, I do not use jQuery....
Use javascript closures. This link may help
http://dev.fyicenter.com/Interview-Questions/AJAX/How_do_I_handle_concurrent_AJAX_requests_.html
function AJAXInteraction(url, callback) {
var req = init();
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
if (req.readyState == 4) {
if (req.status == 200) {
if (callback) callback(req.responseXML);
}
}
}
this.doGet = function() {
req.open("GET", url, true);
req.send(null);
}
this.doPost = function(body) {
req.open("POST", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(body);
}
}
function startCount() {
var ai = new AJAXInteraction("/path/to/count.php", function(){alert("After startCount");});
ai.doGet();
}
function updateTable() {
var ai = new AJAXInteraction("/path/to/update.php", function(){alert("After updateTable");});
ai.doGet();
}
Have the 'onSuccess' of one call initiate the next ajax call. So you would call startCount() and when that returns you fire off updateTable().
function setAjaxConnection(){
//call Ajax here
setAjaxConnectionResponce;
}
function setAjaxConnectionResponce(){
//on readystate==4
startCount();
}
function startCount(){
// code for count
updateTable();
}
function updateTable(){
// code for update
}
<body onLoad="setAjaxConnection();">
I need to set/get the cookies stored at first.example while browsing second.example, I have full access of first.example but I only have JavaScript access (can manipulate the DOM as I want) on second.example.
My first approach was to create an iframe on second.example (with JS) that loaded a page like first.example/doAjax?setCookie=xxx and that did an AJAX call to say first.example/setCookie?cookieData=xxx which would set the cookie on first.example with the data we passed around.
That pretty much worked fine for setting the cookie on first.example from second.example - for getting a cookie I basically followed the same procedure, created the iframe that loaded first.example/doAjax?getCookie and that would do an AJAX call to say first.example/getCookie which would read the cookie info on first.example and return it as a JSON object.
The problem is that I'm unable to bring that JSON cookie object back to second.example so I can read it, well maybe I could just bring it when the AJAX call is complete using "window.top" but there's timing issues because its not relative to when the iframe has been loaded. I hope I am clear and was wondering if there's an easier solution rather than this crazy iframe->ajax crap, also seems like this won't even work for getting cookies in SAFARI.
You could inject a script element into HEAD of the document with a callback that passes the cookie you need to whatever function needs it.
Something like:
<script type="text/javascript">
var newfile=document.createElement('script');
newfile.setAttribute("type","text/javascript");
newfile.setAttribute("src", 'http://first.com/doAjax?getCookie&callback=passCookie');
document.getElementsByTagName("head")[0].appendChild(newfile);
</script>
And the page first.com/doAjax?getCookie could do this:
passCookie({'name':'mycookie', 'value':'myvalue'});
Put this PHP-File to first.com:
//readcookie.php
echo $_COOKIE['cookiename'];
On second.com you can use this javascript to get the value:
function readCookieCallback()
{
if ((this.readyState == 4) && (this.status == 200))
{
alert("the value of the cookie is: "+this.responseText);
}
else if ((this.readyState == 4) && (this.status != 200))
{
//error...
}
}
function buttonClickOrAnything()
{
var refreshObject = new XMLHttpRequest();
if (!refreshObject)
{
//IE6 or older
try
{
refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return;
}
}
}
refreshObject.onreadystatechange = readCookieCallback;
refreshObject.open("GET", "http://www.first.com/readcookie.php");
refreshObject.send();
}
Regards,
Robert
For SETTING cookies you can change my script as follows:
The new PHP-Script:
//writecookie.php
setcookie($_GET['c'], $_GET['v']);
And the JavaScript:
function buttonClickOrAnything()
{
var refreshObject = new XMLHttpRequest();
if (!refreshObject)
{
//IE6 or older
try
{
refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return;
}
}
}
refreshObject.open("GET", "http://www.first.com/writecookie.php?c=cookiename&v=cookievalue");
refreshObject.send();
}
That should work on all browsers.