Change active function from on click to on load - javascript

I have a function that check mobile internet.
This function work of click(OnClick Function)
I would that work automatically when app launch!
How do i do?
The function is this:
<script>
function checkJSNetConnection(){
var xhr = new XMLHttpRequest();
var file = "dot.png";
var r = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?subins=" + r, false);
try {
xhr.send();
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
function onJSButtonclick(){
if(checkJSNetConnection()==true){
alert("Internet Connection Exists");
}else{
alert("Internet Connection Doesn't Exist");
}
}
</script>

Try :
$(document).ready(function(){
onJSButtonclick();
});
Add it just before your closing </script> tag.

Use document.onload = function() {...}; or, if you have jQuery, use `$(document).ready(function() {...});
e.g. using this your script would look like
document.onload = function() {
if (checkJSNetConnection() === true) {
alert("Internet Connection Exists");
} else {
alert("Internet Connection Doesn't Exist");
}
};
or
$(document).ready(function() {
if (checkJSNetConnection() === true) {
alert("Internet Connection Exists");
} else {
alert("Internet Connection Doesn't Exist");
}
});

Related

b4j jquery websockets library sending data issue

I looking for some pointer on how data is sent using a custom library that connects to a java server running as a websocket server.
The code im using to connect which is successful
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="b4j_ws.js"></script>
<script>
// connection to websocket
$( document ).ready(function() {
b4j_connect("/push/ws");
});
</script>
and this is my guess and how to send data using the library which at the moment is not correct, the message would be 'wwww' when sent successfully.
<script>
b4j_ws.send(JSON.stringify({"type":"data","data":"wwww"}));
</script>
These are frames i captured from the working example but it used a button where i want to just use jquery
{"type":"event","event":"btnsend_click","params":{"which":1,"target":"btnsend","pageX":31,"pageY":19,"metaKey":false}}
{"id":"#txt","method":"val","etype":"runmethodWithResult"}
{"type":"data","data":"wwww"}
the library which is b4j_ws.js in the above code.
//B4J WebSockets client library v0.9
/*jslint browser: true*/
/*global $, jQuery, WebSocket*/
/*jshint curly: false */
"use strict";
var b4j_ws;
var b4j_closeMessage = false;
//only called as a result of a server request that is waiting for result.
//this method should not be called in any other case.
function b4j_sendData(data) {
b4j_ws.send(JSON.stringify({type: "data", data: data}));
}
function b4j_raiseEvent(eventName, parameters) {
try {
if (b4j_ws.readyState !== 1) {
if (b4j_closeMessage === false) {
window.console.error("connection is closed.");
window.alert("Connection is closed. Please refresh the page to reconnect.");
b4j_closeMessage = true;
}
} else {
b4j_ws.send(JSON.stringify({type: "event", event: eventName, params: parameters}));
}
} catch (e) {
window.console.error(e);
}
}
function b4j_addEvent(selector, event, eventName, preventDefault) {
var obj = $(selector);
if (obj.length > 0) {
obj.on(event, function (e) {
if (preventDefault) {
e.preventDefault();
e.stopPropagation();
}
b4j_raiseEvent(eventName, {which: e.which, target: e.target.id, pageX: e.pageX, pageY: e.pageY, metaKey: e.metaKey});
});
}
}
function b4j_addAutomaticEvents(data) {
$.each(data, function (index, value) {
b4j_addEvent("#" + value.id, value.event, value.id + "_" + value.event, true);
});
}
function b4j_runFunction(func, params) {
return window[func].apply(null, params);
}
function b4j_eval(params, script) {
var f = new Function(script);
return f.apply(null, params);
}
function b4j_connect(absolutePath) {
if (typeof WebSocket === 'undefined') {
window.alert("WebSockets are not supported by your browser.");
return;
}
var l = window.location, fullpath;
fullpath = ((l.protocol === "https:") ? "wss://" : "ws://") + l.hostname + ":" + l.port + absolutePath;
b4j_ws = new WebSocket(fullpath);
b4j_ws.onmessage = function (event) {
var ed = JSON.parse(event.data);
if (ed.etype === "runmethod") {
$(ed.id)[ed.method].apply($(ed.id), ed.params);
} else if (ed.etype === "runmethodWithResult") {
b4j_sendData($(ed.id)[ed.method].apply($(ed.id), ed.params));
} else if (ed.etype === "setAutomaticEvents") {
b4j_addAutomaticEvents(ed.data);
} else if (ed.etype === "runFunction") {
b4j_runFunction(ed.prop, ed.value);
} else if (ed.etype === "runFunctionWithResult") {
b4j_sendData(b4j_runFunction(ed.prop, ed.value));
} else if (ed.etype === "eval") {
b4j_eval(ed.value, ed.prop);
} else if (ed.etype === "evalWithResult") {
b4j_sendData(b4j_eval(ed.value, ed.prop));
} else if (ed.etype === "alert") {
window.alert(ed.prop);
}
};
}
I change on the click method to a onload method in the java webserver and it worked!

undefined type when i turned my code to Object Javascript AJAX

i don't understand why i get TypeError (this.req is undefined) on line :
if (this.req.readyState === 4) {
function RequestCORS(url) {
this.url = "http://crossorigin.me/" + url;
this.req = new XMLHttpRequest();
}
RequestCORS.prototype.send = function () {
this.req.open("GET", this.url);
this.req.onreadystatechange = function() {
if (this.req.readyState === 4) {
if (this.req.status === 200) {
console.log(this.req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
this.req.send();
};
function main() {
var url = "http://www.01net.com/rss/mediaplayer/replay/";
var requete = new RequestCORS(url);
requete.send();
}
window.addEventListener("load", main);
Thanks for reading.
this.req is undefined because you're making an asynchronous request and by the time your onreadystatechange fires this doesn't refer to your RequestCORS instance anymore.
You could declare a local variable that remains in scope inside the onreadystatechange function.
var req = this.req;
this.req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
console.log(req.responseText);
} else {
console.log("error request");
//handleError
}
}
};
or use bind
this.req.onreadystatechange = function() {
if (this.req.readyState === 4) {
if (this.req.status === 200) {
console.log(this.req.responseText);
} else {
console.log("error request");
//handleError
}
}
}.bind(this);
or get rid of this.req entirely
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status === 200) {
console.log(req.responseText);
} else {
console.log("error request");
//handleError
}
}
};

can't be able to reload the page

function setAction(){
var value;
var id = document.getElementById('id').value;
if(document.getElementById('action1').checked==true){
value = "Active"
}
else if(document.getElementById('action2').checked==true){
value = "Inactive";
}
else{
value = "other";
}
jConfirm('Are you continue?', 'Confirmation Dialog', function(r) {
if(r==true){
var strURL="process.php?task=setActionProposal&id="+id+"&status="+value+"&value="+document.getElementById('other').value;
var req = getXMLHTTP();
if (req) {
document.getElementById('loader').style.display='block'
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//alert(req.responseText);
obj = JSON.parse(req.responseText);
if(obj.valid==true){
document.getElementById('loader').style.display='none';
window.location.href='user.php';
}
}
else {
// alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
else{ }
//jAlert('Confirmed: ' + r, 'Confirmation Results'); });
}
My page is not redirecting what's wrong with this can any one solved out I need to redirect with window.location.href='user.php';
Try with your full project path
ie,
window.location = 'your project path/user.php';
At first,
You check that,
window.location.href = 'http://www.google.com';
this will work correctly.
Then the issue is your project path.

Nested function not work in Mozilla browser

i have call the below function in my application
function workerCall() {
debugger;
if (typeof (Worker) !== "undefined") {
var worker = new Worker("Scripts/worker.js");
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
worker.postMessage({ 'username': Username });
function workerResultReceiver(e) {
$('.NotificationCount').html(e.data);
if (parseInt(e.data) != 0 && currentPage == "Alert") {
StateFlag = false;
$('.Notification').show();
$('.Drildown').each(function () {
var temp = this.id;
if ($('#' + temp).attr('expand') == "true") {
currentTab = temp;
StateFlag = true;
}
});
currentScrollPosition = $('body').scrollTop();
GetAlerts();
} else {
$('.Notification').hide();
}
}
function workerErrorReceiver(e) {
console.log("there was a problem with the WebWorker within " + e);
}
}
else {
}
}
the method will execute in IE,Chrome but when comes to Mozilla i got an error ReferenceError: workerResultReceiver is not defined.How can i resolve this error?
This happens because you are making reference to function that is not created yet. You need to put this:
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
Above
function workerErrorReceiver
line or at the end of the scope.

Second call out of two xmlhttprequest doesn't work

I've read a lot of how to try and make two xmlhttprequest in parallel, but it looks like something doesn't quite work.
I have 1 php file. which includes 2 .js files.
The first runs xmlhttprequest every 3 seconds.
I want the second to run on demand, but whenever i trigger it, it returns with status 4 but the responseText is always empty. (the PHP file prints with no question, i even tried to put on the PHP file just window.open('1') to see that the file is called and its not).
Here is the first JS :
var req1 = createXMLHttpRequest2();
var user_redirected = false;
function createXMLHttpRequest2() {
var ua2;
if(window.XMLHttpRequest) {
try {
ua2 = new XMLHttpRequest();
} catch(e) {
ua2 = false;
}
} else if(window.ActiveXObject) {
try {
ua2 = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua2 = false;
}
}
return ua2;
}
function set_user_redirected_false() {
user_redirected = false;
}
function get_user_redirected() {
return user_redirected;
}
function handleResponse(username, game_id, isInvitation) {
if(req1.readyState == 4 && req1.status==200) {
var response = req1.responseText;
if (response == "true") {
// Ask to set the game_accepted var to 1 (user is redirected and not leaving)
user_redirected = true;
if (isInvitation == "true") {
window.location.href = "game.php?game_id="+game_id+"&position=2";
} else {
window.location.href = "game.php?game_id="+game_id+"&position=1";
}
}
else {
setTimeout(function(){sendRequest();}, 3000);
}
}
}
function sendRequest() {
user_redirected = false;
var username = "";
var game_id = -1;
var isInvitation = "false";
username = document.getElementById("username").value;
game_id = document.getElementById("game_id").value;
isInvitation = document.getElementById("invitation").value;
if (isInvitation == "true") {
req1.open('GET', 'check_for_inviter.php?username='+username+'&game_id='+game_id ,true);
} else {
req1.open('GET', 'check_for_opponent.php?username='+username+'&game_id='+game_id,true);
}
req1.onreadystatechange = function(){handleResponse(username, game_id, isInvitation);};
req1.send(null);
}
This is the second JS file :
function createXMLHttpRequest() {
var ua;
if(window.XMLHttpRequest) {
try {
ua = new XMLHttpRequest();
} catch(e) {
ua = false;
}
} else if(window.ActiveXObject) {
try {
ua = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ua = false;
}
}
return ua;
}
function delete_waiting_games(username) {
var req2 = createXMLHttpRequest();
req2.open('GET', 'delete_waiting_games_for_username.php');
req2.onreadystatechange = function(){
window.open(req2.readyState+'&'+req2.responseText);
};
req2.send(null);
}
As you can see i open a new window to see the response and the ready state (just for testing) and i always get status 4 and empty responseText.
Thanks.
Use setTimeout to separate the calls, and with to encapsulate the XMLHTTPRequest:
function xhr()
{
with(new XMLHttpRequest)
{
open("GET",{},true);
setRequestHeader("Foo", "Bar");
send("");
onreadystatechange = handler;
}
}
function handler(event)
{
!!event.target && !!event.target.readyState && event.target.readyState === 4 && ( console.log(event) );
}
setTimeout(xhr, 500);
setTimeout(xhr, 1000);

Categories