Can't execute an onLoad event - mootools

I have problems using an OnLoad event in a function:
(function () {
var ds = document.createElement('script');
ds.type = 'text/javascript';
ds.async = true;
ds.src = 'http://' + ds_shortname + '.myscript.com/emb.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ds);
ds.onLoad = function(){
alert('ok');
var ds_div = $('ds-div');
if (IsConnected())
{
alert('connect');
}else{
alert('not connect');
}
}
})();
In fact my ds.onLoad doesn't execute and I don't know why. I think it because my function execute herselve but I have no isea how to solve that.
Thanks a lot.

Use the Utilities/Asset classes from More for this, for example like this:
new Asset.javascript('//connect.facebook.net/en_US/all.js', {
onLoad:function(){
$('message').set('text', 'Facebook loaded!');
},
async: true
});
Working sample: http://jsfiddle.net/FU5rk/
Directly related to your problem: you inject the element into the DOM before applying the onLoad event. I'm pretty sure that if the file is in cache, or a really fast download, it's simply loaded before you set the event handler.

Related

variable insert to a blink function

I'm new to HTML and ajax. I'm trying to insert a ip list from flask , to the ajax and trigger the js function to blink.
but somehow I can't find a way to insert the ip variable (response[i]) into the function value column in a right way.
it is to trigger the blink on the required ip tab in html.
function ajaxForm(){
// var form= new FormData(document.getElementById("myform2"));
var data = {"name":"John Doe"}
$.ajax({
url:"{{ url_for('Submit_form') }}",
type:"post",
contentType:'application/json',
data:JSON.stringify(data),
dataType: "json",
processData:false,
// async: false
success:function(response){
// alert(response)
if (response == "success")
{alert("Success !!!" );}
else {
for(i in response)
{
BLINK(response[i]);
}
}
},
// #time out 也进入 error
error:function(e){
// alert(e.)
alert("Failed submit form trigger!!!!");
}
})
}
<script type="text/javascript">
function BLINK(){
var t = null;
function blink() {
var obj = $('input[id="IP"][value=response[i]]') . <---- here
obj.addClass("blink-class");
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
At first, you shoul always provide the HTML code too :) because now we dont know if the issue is there.
So let's try to solve the problem blindly :)
if i see this correctly, you just go wrong on the element and make it even more complicated than it is since you're using jquery, because if u have an ID on your elem, check this out:
// change this:
var obj = $('input[id="IP"][value=response[i]]') . <---- here // .. is your problem :)
obj.addClass("blink-class");
// with the dot you add this obj, which is it self, on it self :) that cant work :)
// you can try:
var obj = $('input[value="' + response[i] + '"]') // with NO dot and no fixed ID!
obj.addClass("blink-class");
// or try this
var obj = $('#' + response[i]);
obj.addClass("blink-class");
// and put the IP into the ID attraktion of your input element.
Second Problem is you are using an undefined variable "ID":
blink(IP); // in your timeout function
but you didnt declare this var, so if i understand your code right then your response[i] should be the IP?
Your function should look like this:
function BLINK(IP) { // <-- here you need the ip as parameter for your: BLINK(response[i]) from ajax
var t = null;
function blink() {
var obj = $('#' + IP) // and put IP in the id from input
obj.addClass("blink-class")
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
try this, if its doesnt work please provide complete html and your css code too, also we could need an eventually error message from console, you can see that by pressing F12 in FireFox or Chrome and then switch to the console tab, press F5 then to reload the page and see errors, post it too please.
Or try out my jsfiddle for you:
https://jsfiddle.net/AIQIA/tjg659sr/17/
You have to remove dots from your IP and put it as id in your elem you wants get to blink, further you need to remove the dots from the response[i] or in your php code before, easy use $ip = preg_replace('/\./','',$ip);
Or use this to use only the complete IP in your input value, then you dont need to remove dots:
https://jsfiddle.net/AIQIA/tjg659sr/21/
greetz Toxi

WebRTC SDP object (local description) by Firefox does not contain DataChannel info unlike Chrome?

I'm testing WebRTC procedure step by step for my sake.
I wrote some testing site for server-less WebRTC.
http://webrtcdevelop.appspot.com/
In fact, STUN server by google is used, but no signalling server deployed.
Session Description Protocol (SDP) is exchanged manually by hand that is CopyPaste between browser windows.
So far, here is the result I've got with the code:
'use strict';
var peerCon;
var ch;
$(document)
.ready(function()
{
init();
$('#remotebtn2')
.attr("disabled", "");
$('#localbtn')
.click(function()
{
offerCreate();
$('#localbtn')
.attr("disabled", "");
$('#remotebtn')
.attr("disabled", "");
$('#remotebtn2')
.removeAttr("disabled");
});
$('#remotebtn')
.click(function()
{
answerCreate(
new RTCSessionDescription(JSON.parse($('#remote')
.val())));
$('#localbtn')
.attr("disabled", "");
$('#remotebtn')
.attr("disabled", "");
$('#remotebtn')
.attr("disabled", "");
});
$('#remotebtn2')
.click(function()
{
answerGet(
new RTCSessionDescription(JSON.parse($('#remote')
.val())));
$('#remotebtn2')
.attr("disabled", "");
});
$('#msgbtn')
.click(function()
{
msgSend($('#msg')
.val());
});
});
var init = function()
{
//offer------
peerCon =
new RTCPeerConnection(
{
"iceServers": [
{
"url": "stun:stun.l.google.com:19302"
}]
},
{
"optional": []
});
var localDescriptionOut = function()
{
console.log(JSON.stringify(peerCon.localDescription));
$('#local')
.text(JSON.stringify(peerCon.localDescription));
};
peerCon.onicecandidate = function(e)
{
console.log(e);
if (e.candidate === null)
{
console.log('candidate empty!');
localDescriptionOut();
}
};
ch = peerCon.createDataChannel(
'ch1',
{
reliable: true
});
ch.onopen = function()
{
dlog('ch.onopen');
};
ch.onmessage = function(e)
{
dlog(e.data);
};
ch.onclose = function(e)
{
dlog('closed');
};
ch.onerror = function(e)
{
dlog('error');
};
};
var msgSend = function(msg)
{
ch.send(msg);
}
var offerCreate = function()
{
peerCon
.createOffer(function(description)
{
peerCon
.setLocalDescription(description, function()
{
//wait for complete of peerCon.onicecandidate
}, error);
}, error);
};
var answerCreate = function(descreption)
{
peerCon
.setRemoteDescription(descreption, function()
{
peerCon
.createAnswer(
function(description)
{
peerCon
.setLocalDescription(description, function()
{
//wait for complete of peerCon.onicecandidate
}, error);
}, error);
}, error);
};
var answerGet = function(description)
{
peerCon.setRemoteDescription(description, function()
{ //
console.log(JSON.stringify(description));
dlog('local-remote-setDescriptions complete!');
}, error);
};
var error = function(e)
{
console.log(e);
};
var dlog = function(msg)
{
var content = $('#onmsg')
.html();
$('#onmsg')
.html(content + msg + '<br>');
}
Firefox(26.0):
RtpDataChannels
onopen event is fired successfully, but send fails.
Chrome(31.0):
RtpDataChannels
onopen event is fired successfully, and send also succeeded.
A SDP object by Chrome is as follows:
{"sdp":".................. cname:L5dftYw3P3clhLve
\r\
na=ssrc:2410443476 msid:ch1 ch1
\r\
na=ssrc:2410443476 mslabel:ch1
\r\
na=ssrc:2410443476 label:ch1
\r\n","type":"offer"}
where the ch1 information defined in the code;
ch = peerCon.createDataChannel(
'ch1',
{
reliable: false
});
is bundled properly.
However, a SDP object (local description) by Firefox does not contain DataChannel at all, and moreover, the SDP is much shorter than Chrome, and less information bundled.
What do I miss?
Probably, I guess the reason that send fails on DataChannel is due to this lack of information in the SDP object by firefox.
How could I fix this?
I investigated sources of various working libraries, such as peerJS, easyRTC, simpleWebRTC, but cannot figure out the reason.
Any suggestion and recommendation to read is appreciated.
[not an answer, yet]
I leave this here just trying to help you. I am not much of a WebRTC developer. But, curious i am, this quite new and verry interresting for me.
Have you seen this ?
DataChannels
Supported in Firefox today, you can use DataChannels to send peer-to-peer
information during an audio/video call. There is
currently a bug that requires developers to set up some sort of
audio/video stream (even a “fake” one) in order to initiate a
DataChannel, but we will soon be fixing that.
Also, i found this bug hook, witch seems to be related.
One last point, your version of adapter.js is different from the one served on code.google. And .. alot. the webrtcDetectedVersion part is missing in yours.
https://code.google.com/p/webrtc/source/browse/stable/samples/js/base/adapter.js
Try that, come back to me with good newz. ?
After last updating, i have this line in console after clicking 'get answer'
Object { name="INVALID_STATE", message="Cannot set remote offer in
state HAVE_LOCAL_OFFER", exposedProps={...}, more...}
but this might be useless info ence i copy pasted the same browser offre to answer.
.. witch made me notice you are using jQuery v1.7.1 jquery.com.
Try updating jQuery (before i kill a kitten), and in the meantime, try make sure you use all updated versions of scripts.
Woups, after fast reading this : https://developer.mozilla.org/en-US/docs/Web/Guide/API/WebRTC/WebRTC_basics then comparing your javascripts, i see no SHIM.
Shims
As you can imagine, with such an early API, you must use the browser
prefixes and shim it to a common variable.
> var PeerConnection = window.mozRTCPeerConnection ||
> window.webkitRTCPeerConnection; var IceCandidate =
> window.mozRTCIceCandidate || window.RTCIceCandidate; var
> SessionDescription = window.mozRTCSessionDescription ||
> window.RTCSessionDescription; navigator.getUserMedia =
> navigator.getUserMedia || navigator.mozGetUserMedia ||
> navigator.webkitGetUserMedia;

Loading google maps asynchronously

I am trying to load my google map asynchronously and it works but it is loading the map in twice. If I remove "box.onload = initialize;" this stops that problem but then the infobox doesn't show...how do I fix my code so it only loads the map once AND shows the infobox.
function loadScript() {
var map = document.createElement('script');
map.type = 'text/javascript';
map.src = 'https://maps.googleapis.com/maps/api/js?key=key_goes_here&sensor=false&callback=initialize';
document.body.appendChild(map);
map.onload = function() {
var box = document.createElement('script');
box.type = 'text/javascript';
box.src = 'https://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js';
document.body.appendChild(box);
box.onload = initialize;
};
}
window.onload = loadScript;
The map appears twice because you're calling initialize twice.
Before fixing that, let's simplify your code a bit. Never let yourself repeat blocks of code like that; instead make it into a common function.
Also, don't load infobox.js from googlecode.com; Google Code is not a CDN. Load your own copy.
So, the code may look like this:
function addScript( url, callback ) {
var script = document.createElement( 'script' );
if( callback ) script.onload = callback;
script.type = 'text/javascript';
script.src = url;
document.body.appendChild( script );
}
function loadMapsAPI() {
addScript( 'https://maps.googleapis.com/maps/api/js?key=key_goes_here&sensor=false&callback=mapsApiReady' );
}
function mapsApiReady() {
addScript( 'infobox.js', initialize );
}
window.onload = loadMapsAPI;
I created this script. You can call this and add any callback function, so you have to just include this to your scripts and call
googleMapsLoadAsync(function(){ alert('google maps loaded'); });
script
var googleMapsAsyncLoaded = false;
var googleMapsAsyncCallback = function(){ };
function googleMapsLoadAsync(callback) {
if (typeof callback !== 'undefined') { googleMapsAsyncCallback=callback; }
if(!googleMapsAsyncLoaded) {
$.getScript('https://maps.googleapis.com/maps/api/js?sensor=false&async=2&callback=googleMapsAsyncLoadedFunction');
} else {
googleMapsAsyncLoadedFunction();
}
}
function googleMapsAsyncLoadedFunction() {
googleMapsAsyncLoaded = true;
if(googleMapsAsyncCallback && typeof(googleMapsAsyncCallback) === "function") {
googleMapsAsyncCallback();
}
googleMapsAsyncCallback = function(){ };
}

Google Maps API Async Loading

I am loading the Google Maps API script Asynchronously in IE9 using the following code:
function initialize() {
...
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
Now the thing is that when the script is fully loaded the initialize() function is called automatically. But when sometimes the user quota has been exceeded the initialize() function is not called and instead of map we see the plain white screen.
I want to detect this and fire my custom function which displays some alert like: "Error!".
Can anyone tell me to how to do this?
Thanks in advance...
As Andrew mentioned, there isn't a direct way to handle this. However, you can at least account for the possibility.
Set a timeout for a reasonable time frame (5 secondes?). In the timeout callback function, test for the existence of google and/or google.maps. If it doesn't exist, assume the script load failed.
setTimeout(function() {
if(!window.google || !window.google.maps) {
//handle script not loaded
}
}), 5000);
// Maps api asynchronous load code here.
I finally found the solution for this problem. Chad gave a nice solution but the only thing is that you can't put that piece of code in the callback() function because if the script fails to load the callback() function is never called!
So based on what Chad has mentioned I finally came up with the following solution:
function initialize() {
...
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
setTimeout(function () {
try{
if (!google || !google.maps) {
//This will Throw the error if 'google' is not defined
}
}
catch (e) {
//You can write the code for error handling here
//Something like alert('Ah...Error Occurred!');
}
}, 5000);
document.body.appendChild(script);
}
window.onload = loadScript;
This seems to work fine for me! :)

In HTML5 is there any way to make Filereader's readAsBinaryString() synchronous

How to wait till onload event completes
function(){
var filedata=null;
reader.onload=function(e){
filedata=e.target.result;
};
reader.readAsBinaryString(file);
//I need code to wait till onload event handler gets completed.
return filedata;
}
Typical solution to this is to separate your code so, that the part which uses the loaded data is in a separate function, which is then called from the event.
Pseudo-code'ish:
function load() {
//load here
reader.onload = function(e) {
process(e.target.result);
}
}
function process(result) {
//finish working here
}
You can read synchronously using threads (Webworkers in Javascript).
http://www.w3.org/TR/FileAPI/#readingOnThreads
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<form><input type="file" id="files" name="file" onchange="upload()" /></form>
function readFile(dfd) {
bytes = [];
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var content = evt.target.result;
//bytes = stringToBytes(content);
dfd.resolve(content);
}
};
reader.readAsBinaryString(file);
}
function upload() {
var dfd = new $.Deferred();
readFile(dfd);
dfd.done(function(content){
alert("content:" + content);
});
}
The answer by Jani is correct, but in the case of dropping multiple files at once in a droparea, there are not separate events for each file (as far as I know). But the idea may be used to load the files synchronously by recursion.
In the code below I load at number of files and concatenate their content into a single string for further proccesing.
var txt="", files=[];
function FileSelectHandler(e) {
e.preventDefault();
files = e.target.files || e.dataTransfer.files;
txt="";
readFile(0);
}
function readFile(n) {
file=files[n];
var reader = new FileReader();
reader.onload = function() {
txt += reader.result;
}
reader.readAsText(file);
if (n<files.length-1) { readFile(n+1); }
else { setTimeout(doWhatEver, 100);}
}
function doWhatEver(){
outtext.innerHTML=txt;
}
The last file also needs a bit of extra time to load. Hence the "setTimeout".
"outtext" is the handle to a textarea where the entire string is displayed. When outputting in at textarea the browser wont' parse the string. This makes it possible to view not only text but also html, xml etc.
No there is not. All IO operations must be asynchronous in Javascript.
Making file operation synchronous would effectively block the browser UI thread freezing the browser. The users don't like that.
Instead you need to design your script in asynchronous manner. It is quite easy with Javascript.