$(window).on('beforeunload', function() not working on sometimes - codeigniter

I have use the below code for window close tab. Its working fine. but sometimes not working.
$(window).on('beforeunload', function() {
var i = "<?php echo $this->uri->segment(4);?>";
var j = "<?php echo $_SERVER["REMOTE_ADDR"];?>";
var k = "<?php echo base_url();?>";
$.ajax({
url: "<?php echo base_url().'home/gethost';?>",
type: "POST",
data: { id : i , ip: j },
datatype : "html"
});
return 'Exit Now!';
});

You have a race condition. As your AJAX request is in flight, the browser is tearing down the page and taking your AJAX request with it. Using synchronous AJAX:
$.ajax({
async: false,
....
will help in some cases (and I've used it myself - empirically, it works) but I don't think anything is guaranteed to work here. Browsers typically put quite severe restrictions on what can be done in beforeunload.

Related

Ajax wait on success before next iteration in .each loop

I have an ajax call inside a .each loop wrapped in a setInterval function.
This handles updating of many divs on a dashboard with just a few lines of code on the html page.
I am worried about server lag vs client side speed. What will happen if the server has not responded with the data before the loop moves on to the next iteration?
So, my question is, can the loop be paused until the success is executed?
Ajax call:
setInterval(function() {
$(".ajax_update").each(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/automated_update/confirmed_appointments.php",
data: "clinic_id=<? echo $clinic_id ?>&tomorrow=<? echo $tomorrow ?>&"+$(this).data('stored'), // serializes the form's elements.
success: function(data)
{
$(data[0]).html(data[1]);
}
});
});
}, 5000); //5 seconds*
</script>
I have looked into .ajaxComplete() but I dont see how to apply this as a solution.
I have also looked at turning the loop into something that calls itself like:
function doLoop() {
if (i >= options.length) {
return;
}
$.ajax({
success: function(data) {
i++;
doLoop();
}
});
}
But would that not interfere with .each? I dont understand how that would play nice with .each and looping based on my div class.
I just cant figure it out! Any help would be appreciated.
I was able to get .when working with the ajax call, but I dont understand how to make .when do what I need (stop the loop until the ajax call is done).
$(".ajax_update").each(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/automated_update/confirmed_appointments.php",
data: "clinic_id=<? echo $clinic_id ?>&tomorrow=<? echo $tomorrow ?>&"+$(this).data('stored'), // serializes the form's elements.
success: function(data)
{
$(data[0]).html(data[1]);
}
});
$.when( $.ajax() ).done(function() {
alert("Finished it");
});
});
After thinking about your question a bit, perhaps a good solution would be to put an event in place that would trigger a new set of updates with a minimum time between your dashboard updates. This would ensure that all your updates process, that we do wait a minimum time between updates and then trigger the update cycle once again. Thus if you DO encounter any delayed ajax responses you do not try another until the previous one has all completed.
I have not fully tested this code but is should do what I describe:
//create a dashboard object to handle the update deferred
var dashboard = {
update: function (myquery) {
var dfr = $.Deferred();
$.ajax({
type: "POST",
dataType: "json",
url: "ajax/automated_update/confirmed_appointments.php",
data: "clinic_id=<? echo $clinic_id ?>&tomorrow=<? echo $tomorrow ?>&" + myquery,
success: dfr.resolve
});
return dfr.promise();
}
};
//create a simple deferred wait timer
$.wait = function (time) {
return $.Deferred(function (dfd) {
setTimeout(dfd.resolve, time);
});
};
// use map instead of your .each to better manage the deferreds
var mydeferred = $(".ajax_update").map(function (i, elem) {
return dashboard.update($(this).data('stored')).then(function (data, textStatus, jqXHR) {
$(data[0]).html(data[1]);
});
});
//where I hang my dashboardupdate event on and then trigger it
var mydiv = $('#mydiv');
var minimumDashboardUpdate = 5000;
$('#mydiv').on('dashboardupdate', function () {
$.when.apply($, mydeferred.get())
.then(function () {
$.when($.wait(minimumDashboardUpdate)).then(function () {
mydiv.trigger('dashboardupdate');
});
});
});
mydiv.trigger('dashboardupdate');

AJAX not saving variables to javascript (asynchronous issues)

Why is alert saying that the text[0] is undefined?
This is my code:
var text = new Array;
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
success: function(rows){
text = rows;
}
});
alert(text[0]);
var text = new Array;
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
success: function(rows){
text = rows;
alert(text[0]); // will work, this gets executed after you set text
}
});
//alert(text[0]); << don't put this here, it will get executed right after you send the request
Finally answered my own question, for anyone that comes across this question, here is what I did:
Because ajax is asynchronous, alert(text[0]) is getting executed before text=rows.
You can set ajax to run procedurally like this:
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
async: false;
success: function(rows){...
Apperently this is one of the few cases that you can/should set ajax to async:false (because you're serving javascript/jquery to the client).

Refreshing data in a div with ajax

I'm developing a Phonegap based app which shows some data that is stored in a remote server. How can I make it refresh data every certain time in case an error happened and it didn't get the data the first time?
this is the list.js
$(document).ready(function(){
var output = $('#vehiculosOutput');
$.ajax({
url: 'http://www.periodicosonofertas.com/mobile/conexVehiculos.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<li>'+item.name + '<p></p>'
+ '<p><font style="white-space:normal; font-size: small" >'+item.descripcion+'</p>' + '<p>'+item.contacto+'</p>' + '<p>'+item.telefono+'</p>' + '<p>'+item.correo+'</p><p>'+status+'</p></li>';
output.append(landmark);
});
},
error: function(){
output.text('Error');
//setTimeout(func.updateStatus, 1000);
}
});
});
You can use long polling for this. In case if you haven't heard about it, this is a good place to start.
If you need to resend the request only in error case, the following snippet would work.
(function poll(delay){
setTimeout(function(){
$.ajax({
url: "http://127.0.0.1:8000/time/",
success: function(data){
$('#requiredDivId').text(data.value);
},
error: function(data){
//Recursive **Poll**
poll(30000);
},
dataType: "json"
});
}, delay);
})(0);
If you want to go with specific feature you mentioned in your comment then there is a function named network.isReachable(You can find more details here) in phonegap. You can put that function to check whether connection is on or not within settimeout function and if its true then you can run function to send data to server.
I hope it'll help you

codeigniter ajax internet explorer

the following code works fine in FF, opera and chrome but fails in IE
function get_modelo(modelo) {
var selState = modelo;
alert (selState);
console.log(selState);
$.ajax({
url: "site/ajax_call", //The url where the server req would we made.
async: false,
type: "POST", //The type which you want to use: GET/POST
data: "state="+selState, //The variables which are going.
dataType: "HTML", //Return data type (what we expect).
//This is the function which will be called if ajax call is successful.
success: function(data) {
//data is the html of the page where the request is made.
$('#city').html(data);
}
})
}
Can't understand the problem.
console.log in IE doesn't work or causes problems.
See here:
What happened to console.log in IE8?
and here:
Testing for console.log statements in IE
and here:
http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
or just google search IE console log
Everything else in your code looks like it would work fine.
Try this. Below will work in IE8 :P
$.ajax({
url: "site/ajax_call", //The url where the server req would we made.
async: false,
type: "POST", //The type which you want to use: GET/POST
data: { state: selState }, //The variables which are going.
dataType: "html", //Return data type (what we expect).
//This is the function which will be called if ajax call is successful.
success: function(data) {
var newDiv = $('<div></div>');
newDiv.html(data);
newDiv.appendTo("#city");
}
});

Get a php variable back after an AJAX action?

When I click onto a button of my page, I do the following action :
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(){
alert("Vote done");
}
Then, the page of the url receive my POST variable to treat the vote:
<?php
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);
// I get the server timestamp
$timestamp_click=time();
if($timestamp_click-$last_timestamp > $time_limit){
$authorization_vote=false;
}else{
$authorization_vote=true;
}
I would like to get back and send $autorisation_vote to AJAX or jQuery in order to alert the user if his vote has been done. I heard about callback but don't succeed to adapt to my case. How do that ?
there's a couple of ways you could do it.
The quick and dirty way is to just echo "true" or "false" in your PHP and that will be available in to the callback function if you declare it like this
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(data){
alert(data);
}
or you could set the http header to return a status code, which would allow you to declare two call backs in your ajax call on success or failure
The php would look like this
<?php
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);
// I get the server timestamp
$timestamp_click=time();
if($timestamp_click-$last_timestamp > $time_limit){
header("HTTP/1.0 423 Locked"); // The resource that is being accessed is locked
}else{
header("HTTP/1.0 204 No Content"); // Processed, but not returning content
}
and your ajax call could look like this
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
statusCode: {
204: function(){ alert("Vote cast"); },
423: function(){ alert("Vote not cast for whatever reason..."); }
}
Which is probably a bit of overkill, but it's good to know these things.
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(data){
alert(data);
}
(note added data)
and in your php script add
echo "vote done and some data here";
because true is changed to 1 and false would be blank
So example:
if($timestamp_click-$last_timestamp > $time_limit){
$authorization_vote=false;
echo "voted";
}else{
$authorization_vote=true;
echo "vote failed";
}

Resources