Callback function doesn't work in firefox - javascript

I'm writting web client for my Exchange Server and I have problem. One of the functions responsible for the getting a current state of user wallet. But after receive answer from server the callback function doesn't work (only in firefox). In Chrome, Opera and Safari it's working good without problem. I'm sure than the problem is on the client side becouse server send completely data.
Code of my function :
proto.on("login", function(status, settings) {
user.waluta = user.currency(settings.waluta);
user.session = settings.idSesja;
proto.getWallet(settings.idSesja, settings.waluta, function(result){
setUserWallet(result);
});
window.location.reload();
});
And code of "getWallet" :
self.getWallet = function(sesja, waluta, callback, successCallback, failureCallback) {
if (self.isConnected()) {
var ses = {
'#class': 'event.IDSesji',
'idSesji': sesja,
'login': self.username
};
self.socket.json.emit('dajPortfel', {
'#class': 'event.DajPortfel',
'waluta': waluta,
'sesja': ses
}, function(data) {
if (data.kod == ResultStatus.ok) {
callback(data.zalacznik);
if (isFunc(successCallback)) successCallback(data.zalacznik);
} else {
if (isFunc(failureCallback)) failureCallback(data.kod);
}
});
} else {
if (isFunc(jobDoneHandler)) { jobDoneHandler(ResultStatus.notConnected); }
}
}

Related

JavaScript navigator.geolocation not executing

I'm building a new site and I'm trying to get a client's coords through the browser using navigator.geolocation. It seems to do nothing at all. It doesn't throw an error or call the callback function. I went to another website using geolocation and it worked. My browser doesn't even ask for my permission on my site. I'm stumped. Thanks for your thoughts.
<script>
navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
function getCoor(pos)
{
var c = pos.coords;
alert(c.latitude);
}
function errorCoor
{
alert("FAILED!");
}
</script>
EDIT: Here is an exact copy and paste of my script:
$(document).ready(function(){
$("#c-other-source").hide();
$("#c-name").focus();
$("#c-phone").mask('(000) 000-0000');
$("#c-source").change(function(){
if ($(this).val() == 7)
{
$("#c-other-source").fadeIn("slow", function(){
$(this).focus();
});
}
});
$("#c-loc").focus(function(){
navigator.geolocation.getCurrentPosition(getCoor, errorCoor, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
});
});
function getCoor(pos)
{
alert(pos.latitude);
}
function errorCoor()
{
alert("failed");
}
Actually, it is throwing the error function now...

Trouble using Notification API js

I'm facing an issue trying to implement notifications in my website.
In fact, I'm trying to make a function that calls PHP with an ajax request, in order to check with mysql if there are any notification. Then, if there is one/few notification(s), I get back from PHP the information I need, and display them using notification API. I do this every 5 seconds.
In fact, notifications are displayed in the top right corner, and I can only see the bottom of it.
Other weird fact, when I use function alert();, notifications are properly displayed.. This issue is happening with Firefox, but not on chromium.
So my question is, do you have any idea why notifications are not placed properly on firefox but not on Chromium? If you need any more information do not hesitate. Thanks in advance, and if you need it, here is some code :
With this two functions, I get what I need thanks to a php script.
function notifications() {
$.ajax({ url: './get_notifications.php/',
type: 'post',
data: {"name": window.user},
success: function(output) {
if (output != "")
{
split_notifications(output);
}
else
return;
},
failure: function() {
console.log("failed");
}
});
}
function check_notifications() {
setInterval(function() {
notifications();
}, 10000);
}
In this function, I just split information and then call another function, in charge of creating my notification.
function split_notifications(notif) {
var tmp_notif = notif.split(";");
var index = 0;
while (tmp_notif[0].split(",,,")[index])
{
//!\\ When I put alert() HERE it's working
display_notification(tmp_notif[1].split(",,,")[index], tmp_notif[2].split(",,,")[index], tmp_notif[0].split(",,,")[index]);
index += 1;
}
}
Here is the function that creates my notification :
function display_notification(title, message, someone) {
{
if(window.Notification && Notification.permission !== "denied") {
Notification.requestPermission(function(status) { // status is "granted", if accepted by user
var project_notification = new Notification(title, {
body: someone + " " + message + '\nSee more...',
icon: "../img/" + someone.split(" ")[1] + ".png"
});
project_notification.onclick = function() {
alert("");
}
});
}
}

issue with an asynchronous while in WinJS

I have an app which invokes a WebService (callPathsToMultiTiffWS) which have two possibilities:
complete = true
complete = false
in the case complete = false I want to show a dialog which notifies to user than webService failed and two buttons:
retry action (reinvoke WS)
Exit
this is my code so far:
callPathsToMultiTiffWS(UID_KEY[9], stringCapturePaths, UID_KEY[1], UID_KEY[2], UID_KEY[3], UID_KEY[4], UID_KEY[5], UID_KEY[6]).then(
function (complete) {
if (complete == true) {//if true, it stores the id of the picture to delete
Windows.UI.Popups.MessageDialog("WS executed successfully", "Info").showAsync().then(function (complete) {window.close();});
} else {
var messageDialogPopup = new Windows.UI.Popups.MessageDialog("An error occur while calling WS, retry??", "Info");
messageDialogPopup.commands.append(new Windows.UI.Popups.UICommand('Retry', function () { /*code for recall element*/ }));
messageDialogPopup.commands.append(new Windows.UI.Popups.UICommand('Exit', function () { /*code for exit*/ }));
messageDialogPopup.showAsync();
_divInput.innerHTML = "";
}
},
function (error) { console.log("function error"); });
This works good so far, but I want the recall feature working
so I thought to embedd my code inside a loop like this
var ban = true;
while (true) {
callPathsToMultiTiffWS(UID_KEY[9], stringCapturePaths, UID_KEY[1], UID_KEY[2], UID_KEY[3], UID_KEY[4], UID_KEY[5], UID_KEY[6]).then(
function (complete) {
if (complete == true) {//if true, it stores the id of the picture to delete
Windows.UI.Popups.MessageDialog("WS executed successfully", "Info").showAsync().then(function (complete) { window.close(); });
} else {
var messageDialogPopup = new Windows.UI.Popups.MessageDialog("An error occur while calling WS, retry??", "Info");
messageDialogPopup.commands.append(new Windows.UI.Popups.UICommand('Retry', function () { ban == true; }));
messageDialogPopup.commands.append(new Windows.UI.Popups.UICommand('Exit', function () { ban == false; }));
messageDialogPopup.showAsync().then(function (complete) {
console.log("no ps no");
});
}
},
function (error) { console.log("function error"); });
if (ban == false) break;
}
this loop executes the webService, but it doesn't wait for user interaction to trigger the webservice by touching one of the buttons, it is an endless loop with calls to my webService, how to fix this??
thanks in advance for the support
If I'm not missing something, it looks like the error is caused because your code isn't designed to run the next set of tasks after the asynchronous call to showAsync returns. Because the call to showAsync is non-blocking, the while loop will start over again and make another call to the Web service. And because THAT call (callPathsToMultiTiffWS) is also non-blocking, the loop will start over again, triggering another call to callPathsToMultiTiffWS. And over again, and again.
My recommendation is to break out the next call to the Web service so that it will only be triggered when the user makes a selection. If you separate your concerns (move the calls to the Web service into different function or module than the UI that informs the user of an issue), then you can probably fix this.
Kraig BrockSchmidt has a great blog post about the finer details of Promises:
http://blogs.msdn.com/b/windowsappdev/archive/2013/06/11/all-about-promises-for-windows-store-apps-written-in-javascript.aspx
-edit-
Here's some code that I wrote to try to demonstrate how you might accomplish what you're trying:
function tryWebServiceCall(/* args */) {
var url = "some Web service URL";
return new WinJS.xhr({ url: url }).then(
function (complete) {
if (complete) {
return new Windows.UI.Popups.MessageDialog("WS executed successfully", "Info").showAsync().then(
function () { /*do something */ });
} else {
var messageDialogPopup = new Windows.UI.Popups.MessageDialog("An error occur while calling WS, retry??", "Info");
messageDialogPopup.commands.append(new Windows.UI.Popups.UICommand('Retry', function () {
return tryWebServiceCall( /* args */);
}));
messageDialogPopup.commands.append(new Windows.UI.Popups.UICommand('Exit', function () { return; }));
return messageDialogPopup.showAsync();
}
});
}

Check Internet connectivity with jquery

I am trying to check for the internet connection by sending a GET request to the server. I am a beginner in jquery and javascript. I am not using navigator.onLine for my code as it works differently in different browsers. This is my code so far:
var check_connectivity={
is_internet_connected : function(){
var dfd = new $.Deferred();
$.get("/app/check_connectivity/")
.done(function(resp){
return dfd.resolve();
})
.fail(function(resp){
return dfd.reject(resp);
})
return dfd.promise();
},
}
I call this code in different file as:
if(!this.internet_connected())
{
console.log("internet not connected");
//Perform actions
}
internet_connected : function(){
return check_connectivity.is_internet_connected();
},
The is_internet_connected() function returns a deferred object whereas I just need an answer in true/false. Can anybody tell me about how to achieve this?
$.get() returns a jqXHR object, which is promise compatible - therefore no need to create your own $.Deferred.
var check_connectivity = {
...
is_internet_connected: function() {
return $.get({
url: "/app/check_connectivity/",
dataType: 'text',
cache: false
});
},
...
};
Then :
check_connectivity.is_internet_connected().done(function() {
//The resource is accessible - you are **probably** online.
}).fail(function(jqXHR, textStatus, errorThrown) {
//Something went wrong. Test textStatus/errorThrown to find out what. You may be offline.
});
As you can see, it's not possible to be definitive about whether you are online or offline. All javascript/jQuery knows is whether a resource was successfully accessed or not.
In general, it is more useful to know whether a resource was successfully accessed (and that the response was cool) than to know about your online status per se. Every ajax call can (and should) have its own .done() and .fail() branches, allowing appropriate action to be taken whatever the outcome of the request.
Do you mean to check the internet connection if it's connected?
If so, try this:
$.ajax({
url: "url.php",
timeout: 10000,
error: function(jqXHR) {
if(jqXHR.status==0) {
alert(" fail to connect, please check your connection settings");
}
},
success: function() {
alert(" your connection is alright!");
}
});
100% Working:
function checkconnection() {
var status = navigator.onLine;
if (status) {
alert('Internet connected !!');
} else {
alert('No internet Connection !!');
}
}
This piece of code will continue monitoring internet connection
click bellow "Run code snippet" button and see it in action.
function checkInternetConnection(){
var status = navigator.onLine;
if (status) {
console.log('Internet Available !!');
} else {
console.log('No internet Available !!');
}
setTimeout(function() {
checkInternetConnection();
}, 1000);
}
//calling above function
checkInternetConnection();
try this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
if (! window.jQuery) {
alert('No internet Connection !!');
}
else {
// internet connected
}
Jquery Plugin for Detecting Internet Connection
you cannot get simple true or false in return, give them a callback handler
function is_internet_connected(callbackhandler)
{
$.get({
url: "/app/check_connectivity/",
success: function(){
callbackhandler(true);
},
error: function(){
callbackhandler(false);
},
dataType: 'text'
});
}
I just use the navigator onLine property, according to W3C http://www.w3schools.com/jsref/prop_nav_online.asp
BUT navigator only tells us if the browser has internet capability (connected to router, 3G or such).
So if this returns false you are probably offline but if it returns true you can still be offline if the network is down or really slow.
This is the time to check for an XHR request.
setInterval(setOnlineStatus(navigator.onLine), 10000);
function setOnlineStatus(online)
{
if (online) {
//Check host reachable only if connected to Router/Wifi/3G...etc
if (hostReachable())
$('#onlineStatus').html('ONLINE').removeAttr('class').addClass('online');
else
$('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
} else {
$('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
}
}
function hostReachable()
{
// Handle IE and more capable browsers
var xhr = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP");
var status;
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open("HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
// Issue request and handle response
try {
xhr.send();
return (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304));
} catch (error) {
return false;
}
}
EDIT: Use port number if it is different than 80, otherwise it fails.
xhr.open("HEAD", "//" + window.location.hostname + ":" + window.location.port + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
It's working fine for me.
<div id="status"></div>
<script>
window.addEventListener("offline", (event) => {
const statusDisplay = document.getElementById("status");
statusDisplay.textContent = "OFFline";
});
window.addEventListener("online", (event) => {
const statusDisplay = document.getElementById("status");
statusDisplay.textContent = "Online";
});
</script>

Simple AJAX request using jQuery not working on IE

This is my code, which sometimes works and sometimes doesn't.
var resolve_ajax_login=function(){
$.ajaxSetup({cache:false });
var loginvar=$("#inputlogin").attr("value");
var senhavar=$("#inputsenha").attr("value");
$.post("../model/php/login_ajax.php",
{login:loginvar, senha:senhavar},
function(responseText){
if (responseText=="ok"){
window.location="areatrab.php";
}else{
$("#inputlogin").attr("value","");
$("#inputsenha").attr("value","");
$("#divmensagem").html("<span style='color:red;font-size:70%;'>"+responseText+"</span>");
}
}
);
return false;
};
Ok. It's in portuguese but I think you get the general picture. Sometimes this works, no problem, but some other times (only in IE, no problem whatsoever in Firefox) it throws a javascript error in my jquery.js file (minified). The error description is as follows:
Object doesn't support this property or method: jquerymin.js line 123 character 183..
which amounts to...
{return new A.XMLHttpRequest}
somewhere in the middle of the jquery.js file. It seems to be very IE-specific, as I had no such problems on Firefox. This guy apparently had the same problem as I did, but got no responses yet.
Has anyone else seen this? Thanks in Advance
P.S.: I run IE 8
Have you tried using a full URL instead of ../model...? For example: http://www.mysite.com/model/login_ajax.php
Also, maybe try modifying the 'xhr' property using jQuery's .ajax method... something like:
var loginvar = $("#inputlogin").val();
var senhavar = $("#inputsenha").val();
var ajax_obj = null;
var resolve_ajax_login = function() {
if(ajax_obj !== null) {
try {
ajax_obj.abort();
} catch(e) {
}
}
ajax_obj = $.ajax({
type: 'POST',
cache: false,
url: '../model/php/login_ajax.php',
data: {login:loginvar, senha:senhavar},
dataType: 'text',
timeout: 7000,
success: function(data)
{
if(response == 'ok') {
alert("right on!");
} else {
alert("not ok");
return;
}
},
error: function(req, reqStatus, reqError)
{
alert("error");
return;
},
'xhr': function() {
if(ajax_obj !== null) {
return ajax_obj;
}
if($.browser.msie && $.browser.version.substr(0,1) <= 7) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
return new XMLHttpRequest();
}
}
});
}
It's something to do with the order in which you try all the different types of browsers in order to create the right kind of XMLHTTP REQUEST object.. I'll explain it in more detail in the following page:
AJAX inconsistency in IE 8?

Categories

Resources