Issue calling a js function on load in index.html - javascript

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

Related

callback function for location.href

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");
})

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 }

SignalR Javascript client callback not firing when using Clients.Group

I'm using SignalR RC2, this is my hub
public class ImgHub : Hub
{
public void Create(string guid)
{
Groups.Add(Context.ConnectionId, "foo");
}
public void SendMsg(string msg)
{
Clients.Group("foo").send(msg);
}
}
I have a console application and a webapplication (asp.net webforms) that connect to this hub. the console application works just as I would expect, the problem is in the Javascript part. The "send" callback doesn't fire when I'm using Clients.Group in SendMsg, if I change SendMsg to this
public void ShareImage(byte[] image, string guid)
{
Clients.All.ReceiveImage(image);
}
it works. Here is the Javascript code
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/jquery.signalR-1.0.0-rc2.min.js"></script>
<script src="http://localhost:4341/signalr/hubs/" type="text/javascript"></script>
<script type="text/javascript">
var mainHub;
$(function () {
$.connection.hub.url = 'http://localhost:4341/signalr';
// Proxy created on the fly
mainHub = $.connection.imgHub;
mainHub.client.send = function (msg) {
alert(msg);
};
// Start the connection
$.connection.hub.start(function() {
mainHub.server.create('vanuit den JS');
})
.done(function() {
$('#msgButton').click(function() {
mainHub.server.sendMsg("msg from JS");
});
});
});
</script>
as you can see in the JS code, I also have a button on the page that calls the SendMsg function, the message does arrive on the console application so I would guess that the JS client is correctly registered in the SignalR group.
I'm no JS specialist so I hope someone that knows more about it then I do can help me out here.
It's because you need to enable rejoining groups in global asax.
GlobalHost.HubPipeline.EnableAutoRejoiningGroups();
There's more detail about that here:
http://weblogs.asp.net/davidfowler/archive/2012/11/11/microsoft-asp-net-signalr.aspx
This method call is going away for 1.0 RTM but for now you need to do it.
One of the reasons why your send function may not be executing is because by the time you are allowing a call to sendMsg on the client the client may not be in the group "foo" yet.
In your $.connection.hub.start you're registering a function to be called when start has completed, but you're also then registering another function to be called once start has completed via the .done. Therefore, what's happening is both functions are firing almost simultaneously. So when the sendMsg function is available to be called you may not have been successfully added to the group.
Here's how you can fix that problem:
$.connection.hub.start().done(function() {
mainHub.server.create('vanuit den JS').done(function() {
$('#msgButton').click(function() {
mainHub.server.sendMsg("msg from JS");
});
});
});
Essentially I'm waiting until the group join has completed successfully until allowing a sendMsg to go through.
I know that this is a long shot answer since you're probably waiting a significant amount of time after the connection has been started and still nothings coming over the wire but I'm unable to replicate the behavior on my end.
If my fix above does not work you should ensure that your server side functions are being called by setting break points.

jQuery's .getScript()... what am I doing wrong?

I'm programming an iPhone app with Phonegap. I have local .html and .js files. The following is in my index.html file:
function onBodyLoad() {
document.addEventListener("deviceready", deviceReady, false);
}
function deviceReady() {
$.getScript("js/order.js");
}
I researched and researched, but just can't figure out why my "order.js" file isn't getting called by the $.getScript method. Any ideas? Or is there any other way to call this .js file within the deviceReady function in my index.html?
For me the following solution worked very well.
Add a custom jQuery function that uses ajax and caches the loaded script:
function init()
{
// Create a custom cached script importer based on ajax
jQuery.cachedScript = function(url, options)
{
// Allow custom options, but dataType, cache and url are always predefined
options = $.extend(options || {},
{
dataType: "script",
cache: true,
url: url
});
return jQuery.ajax(options);
};
importScripts();
}
Import the scripts and optionally handle done and fail:
function importScripts()
{
$.cachedScript("js/events.js")
// Wait for the script to be loaded, before adding the listener
.done(function()
{
document.addEventListener("deviceready", onDeviceReady, false);
});
$.cachedScript("js/navigation.js");
$.cachedScript("js/mark.js");
}
Thats it : )
More information may be found here.

jQuery.getScript() behaviour

Could someone please explain the behaviour of jQuery's getScript() function?
Consider a javascript file test.js:
var tmp = 'a variable';
alert('here');
When test.js is loaded via html's <script> tag, everything works fine: tmp variable is available in the global scope and a message box appears.
I'm trying to get the similar behavior via this code:
<script>
$(document).ready(function() {
$.getScript("static/js/proto/test.js");
setTimeout(function() {
// at this point tmp should be available
// in the global scope
alert(tmp);
} , 2000); // 2 seconds timeout
}
</script>
But browser's error console reports an "Undefined variable tmp" error.
What am I doing wrong?
Thank you.
$.getScript may be asynchronous, use the callback parameter:
$.getScript("static/js/proto/test.js", function() {
// here you are sure that the script has been executed
});
See the documentation for $.getScript: http://api.jquery.com/jQuery.getScript
The real problem with the script was my lack of experience with JS in general and particulary in AJAX: I was trying to run this script on a local machine without a web server.
Guess what: AJAX expects status '200' from a web server to load a document asynchronously. As there was no web server, the status of the async call was '0'.
Thank you everyone for answering.

Categories

Resources