callback function for location.href - javascript

We have below code
Javascript:
function Download() {
//Show Loading Spinner
location.href = "FileDownloadHandler.ashx";
//Some Code(Hiding Loading Spinner)
}
aspx page:
<input type="button" value="Download" onclick="Download();" />
"FileDownloadHandler" will download the file to the user.
Actual Result:
Code below location.href is executing immediately without completion of handler execution.
Expected Result:
I want to stop executing "SomeCode" until handler completes the execution.
How can I achieve this?
Thanks in advance.

Finally I found a solution to my problem. Using jQuery plugin we can achieve this. I have implemented it and working like a charm.
This Plugin does file download and it has successs & failure callbacks, so we can have control on the code which should execute after completion of file download.
Here instead of location.href, we have to call this plugin to invoke our FileDownloadHandler as below.
$("#loading").show();
$.fileDownload('FileDownloadHandler.ashx', {
successCallback: function (url) {
$("#loading").hide();
},
failCallback: function (html, url) {
$("#loading").hide();
alert("Failed");
}
});
More details below
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
http://jqueryfiledownload.apphb.com/
http://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js

Consider using the Jquery get function: https://api.jquery.com/jquery.get/
$.get("FileDownloadHandler.ashx", function() {
alert("Called Ashx Page");
})
.done(function() {
alert("Stuff to do after ashx");
})

Related

async onload not working in this case

I have some code to asynchronously load an Ad on my site which looks like this:
<div id="ad-div"></div>
<script>function onAdReady() {
debug_log('Method onAdReady called');
new Ad(document.getElementById("ad-div"))
}
</script>
<script src="http://content.xxxxx.com/ads/ads.min.js" async onload="onAdReady()"></script>
The problem is that the onAdReady function is never beeing called. The reason for this might be that the html code which contains this snippet is beeing loaded via javascript in the first place like this:
// Initiate out_window_view
$.ajax({
url: loadPagePath("main.html"),
success: function (result) {
debug_log("Going in main.html view");
$("#content").html(result);
},
error: function (result) {
debug_log("Error, failed to load out_window_main view");
}
});
This code is beeing executed in the $(document).ready(function () {] in case that might matter.
Can anyone expalain to me why this is not working and provide me with a workaround or alternative way for solving this issue?
I don't understand why you need to add async to an ajax-generated-content. The purpose of async script is to allow the browser to keep on parsing the document without waiting for the script to fully load. The onload event is called immediately after the script has finished loading and before DOMReady. In other words, async's onload will not fire after DOMReady.
When you add the snippet to your page, the page has already finished parsing, so the async onload event won't fire.
The solution IMO is to remove the async part and just call the function after the <script> synchronously.
You want to load an ad when the page is loaded?
What do you see in the network tab from the debug tools (firebug or F12 in chrome/Firefox)?
Where do you call $( document ).ready() ?
https://learn.jquery.com/using-jquery-core/document-ready/
Can you tell me when you want to send the HTTP request?
If you are able to add the script programmatically, it will be async by default (reference here), and you can listen to the onload or onreadystatechange event (as you can read here, IE11 doesn't support onreadystatechange). Here is an example:
var setup = function(){
console.log('the script has been parsed');
};
var script = document.createElement("script");
script.src = "http://content.xxxxx.com/ads/ads.min.js";
document.getElementsByTagName("head")[0].appendChild(script);
// standard browser
script.onreadystatechange = function (){
if (this.readyState == 'complete'){
setup();
}
}
// IE
script.onload = setup;

Issue calling a js function on load in index.html

I wan to call a js function when the index.html loads.
This js function is defined in main.js file.
I am able to call it using the below way
<input type="button" value="Submit" onclick="getSecretData()" />
But i want this function to be called every time the index.html is loaded (instead of the button)
I tried the below code. Its not working. Can you please help ?
index.html
<script>
$(document).ready(function() {
getSecretData();
});
</script>
main.js
function getSecretData(){
var invocationData = {
adapter: "DummyAdapter",
procedure: "getSecretData",
parameters: []
};
WL.Client.invokeProcedure(invocationData, {
onSuccess: getSecretData_Callback,
onFailure: getSecretData_Callback
});
}
function getSecretData_Callback(response){
alert("getSecretData_Callback response :: " + JSON.stringify(response));
}
Thanks
You are using Worklight. Did you read the training materials?
Other answers given here could work for you, but because you are using Worklight, you should do it in the more appropriate approach for Worklight-based applications.
In your Worklight application, in common\js\main.js, there is wlCommonInit().
If you want some code to run when you start your app, place it there.
function wlCommonInit() {
myFunction();
}
function myFunction(){
// whatever you want to run...
}
Note though, that it is not smart to invoke adapters on application startup. Adapters require connection to the Worklight Server, so what you want to do is to first try and connect to the server using WL.Client.connect and if you succeed in doing so, only then invoke the adapter via the connect's onSuccess callback.
WL.Client.connect({onSuccess: myFunction, onFailure: connectionFailure});
For example:
function wlCommonInit() {
WL.Client.connect({
onSuccess: myFunction,
onFailure: connectionFailure
});
}
function myFunction(){
// whatever you want to run...
}
function connectionFailure(){
// ...
}
You can try this.
document.querySelector('body').addEventListener("load", getSecretData, false);
For more information I recommend reading this previous answer or MDN's page

JQuery start file download then run a function

I have the following jQuery code that redirects to download a file after certain amount of seconds. In that time, I am showing a please wait icon. Once the file download has started by redirecting to the new URL, I want to be able to also then run a function called unloadFrame(). Problem is that because the the page is changing, I cannot run the unloadFrame function.
Any ideas how I can achieve this?
$(document).ready(function () {
window.setTimeout(function () {
location.href = "export.xls";
unloadFrame();
}, 5000)
});
Thanks.
UPDATE
OK i've done the following which seems to work. does anyone have any other ideas or better options:
$(document).ready(function () {
location.href = "export.xls";
window.setTimeout(function () {
unloadFrame();
}, 8000)
});
You cannot download a file like that with JavaScript. Maybe create an iframe, set it's URL to something that returns a download page (with the appropriate HTTP headers), then do your unloadFrame.

how to load google client.js dynamically

this is my first time to post here on stackoverflow.
My problem is simple (I think). I am tasked to allow users to sign up using either Facebook, Google Plus, LinkedIn and Twitter. Now, what I want to do is when the user clicks the Social Network button, it will redirect them to the registration page with a flag that determines which social network they want to use. No problem here.
I want to load each API dynamically depending on which social network they choose.
I have a problem when loading the Google JS API, dynamically. The sample found in here loads client.js in a straightforward manner. I have no problems if I follow the sample code. But I want to load it dynamically.
I tried using $.ajax, $.getScript and even tried adding the script to the page just like how you call Google Analytics asynchronously. None of the above worked. My call back function is NOT called all the time. Also, if i call the setApiKey from the call back function of $.ajax and $.getScript, the gapi.client is NULL. I don't know what to do next.
Codes that did not work:
(function () {
var gpjs = document.createElement('script'); gpjs.type = 'text/javascript'; gpjs.async = false;
gpjs.src = 'https://apis.google.com/js/client.js?onload=onClientLoadHandler';
var sgp = document.getElementsByTagName('script')[0]; sgp.parentNode.insertBefore(gpjs, sgp);})();
Using $.getScript
$.getScript("https://apis.google.com/js/client.js?onload=onClientLoadHandler", function () {
console.log("GP JS file loaded.");
SetKeyCheckAuthority();});
Using $.ajax
$(document).ready(function () {
$.ajax({
url: "https://apis.google.com/js/client.js?onload=onClientLoad",
dataType: "script",
success: function () {
console.log("GP load successful");
SetKeyCheckAuthority();
},
error: function () { console.log("GP load failed"); },
complete: function () { console.log("GP load complete"); }
});});
May I know what is the proper way of calling this js file dynamically? Any help would be appreciated. Thank you.
Ok, I just thought of a solution but i think it's a bad one. Please let me know what you think of it.
i used $.getScript to load the js file
$.getScript("https://apis.google.com/js/client.js?onload=onClientLoadHandler", function () {
console.log("GP JS file loaded.");
SetKeyCheckAuthority();});
and then on my SetKeyCheckAuthority function i placed a condition to call itself after 1 second when gapi.client is null.
function SetKeyCheckAuthority() {
if(null == gapi.client) {
window.setTimeout(SetKeyCheckAuthority,1000);
return;
}
//set API key and check for authorization here }

ASP.NET AJAX: Executing Javascript code before firing request

How can you execute some JavaScript before an Ajax request happens? I'm already using the following;
function pageLoad() {
var manager = Sys.WebForms.PageRequestManager.getInstance();
manager.add_beginRequest(OnBeginRequest);
}
function OnBeginRequest(sender, args) {
}
but that seems to be executing simultaneously to the firing of the request, and that's not helpful to me. Any thoughts, ideas? I also use JQuery so if there's some kind of an alternative that i could use please let me know.
There's another event that happens when you initialize the request, the initializeRequest event.
Use it via add_initializeRequest(), like this:
function pageLoad() {
var manager = Sys.WebForms.PageRequestManager.getInstance();
manager.add_initializeRequest(OnInitializeRequest);
}
function OnInitializeRequest(sender, args) {
//do stuff
}

Categories

Resources