Need to change code to periodically execute (autosave) - javascript

This is working code. If click button, code executes
$(document).ready(function() {
$("#register").click(function(){
if ($("#is_row_changed1").val() > 0) {
$.post(
"_autosave.php",
$("#form1").serialize(),
function(data) {
$('#load').html(data);
document.getElementById('is_row_changed1').value = 0;
}//function(data) {
);//$.post(
//var str = $("#form1").serialize();//this will display in #stage2 all input values like date_day1=22&date_month1=04
//$("#stage2").text(str);
}//if ($("#is_row_changed1").val() > 0) {
});//$("#register").click(function(event){
});//$(document).ready(function() {
I need it execute periodically, for example each 5 seconds
If $(document).ready(function() { change to function autosave() {
var t = setTimeout("autosave()", 5000); nothing happens.
What would be correct code?
Update
Seems got working code. Please, any comments (may be something incorrect/not good)
$(document).ready(function() {
$(function() {
setTimeout(autoSavePost, 5000);
});
function autoSavePost() {
//$("#register").click(function(){
if ($("#is_row_changed1").val() > 0) {
$.post(
"_autosave.php",
$("#form1").serialize(),
function(data) {
$('#load').html(data);
document.getElementById('is_row_changed1').value = 0;
}//function(data) {
);//$.post(
//var str = $("#form1").serialize();//this will display in #stage2 all input values like date_day1=22&date_month1=04
//$("#stage2").text(str);
}//if ($("#is_row_changed1").val() > 0) {
setTimeout(autoSavePost, 5000);
}//function autoSavePost() {
//});//$("#register").click(function(event){
});//$(document).ready(function() {

It seems fine, one change that i might do will be is to use setInterval
$(document).ready(function() {
function autoSavePost() {
if ($("#is_row_changed1").val() > 0) {
$.post("_autosave.php", $("#form1").serialize(), function(data) {
$('#load').html(data);
$('#is_row_changed1').val(0)
});
}
}
setInterval(autoSavePost, 5000);
});

Related

jQuery - If browser tab is focused, then do AJAX - Not working

I have a code that determines if current browser window or tab is active. If it's active, the title of the tab says "active" and if not it says "blurred"
It is working fine. Here's the code:
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
document.title = 'focus';
}
}
$(this).data("prevType", e.type);
})
The code above is working fine.
Now if I add AJAX to it, it doesn't work.
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
var interval = function () {
$.ajax({
url: "<?php echo base_url('home/get') ?>",
cache: false,
success: function (html) {
$("#text").val(html);
document.title ='focus';
},
});
};
setInterval(interval, <?php echo $int ?>);
}
}
$(this).data("prevType", e.type);
})
It says focused if it's in focus. If I go out of focus, it says "blurred" for less than a second, then says focus again. I don't know why. I want it to say blurred if it's not in focus. Adding the AJAX code doesn't make it work.
Please help. Thanks.
You need to use clearTimeout() in your blur event. My code continuously polls my server for data, but when I go out of the page, it stops polling. Please look at the implementation below. I have done the similar one in my application here:
$(window).blur(function() {
clearTimeout(getJsonTmr);
clearTimeout(updatePreviewTmr);
}).focus(StartTimers);
function StartTimers () {
// Every half a second,
getJsonTmr = setInterval(function () {
$.get("/doodles/update?getJson&DoodleID=" + DoodleOptions.DoodleID, function (data) {
data = JSON.parse(data);
if (!DoodleOptions.isActive)
clearDoodleCanvas();
$.each(data, function (index) {
drawFromStream(data[index]);
});
});
}, 500);
updatePreviewTmr = setInterval(function () {
$.post("/doodles/update?updatePreview", {
"DoodleID": DoodleOptions.DoodleID,
"DoodlePreview": canvas.toDataURL()
});
}, 5000);
}
StartTimers();
You can use the above code as reference and change yours.
A simple reference implementation for you...
function timers() {
tmrAjax = setInterval(function () {
$.get(/* ... */);
}, 1000);
}
timers();
$(window).blur(function () {
clearInterval(tmrAjax);
}).focus(timers);

Loader auto-fades in (jQuery/javascript/Bootstrap)

I'm probably an idiot, but I can't find where's problem.
There is a "Suggest a word" button at the bottom of this page.
After filling out the form and clicking on send a loader shows up, however, it doesn't disappear when ajax finishes (it fades out and fades in unexpectedly).
I have no idea why it fades in again and I can't find the reason behind this.
Here is the most important piece of code (I hope so).
$('#suggestQuestionModal').on('show.bs.modal', function (e) {
var currFormGroup = 0;
var maxFormGroups = 4;
//while(currFormGroup < maxFormGroups) {
$('#suggestionSend').click(function() {
if (validator.form()) {
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestLoading").fadeIn('slow');
$("#suggestionSend").attr('disabled', true);
});
if ($("#suggest-email").val() != '' && $("#suggest-want-mail").prop('checked'))
email = $("#suggest-email").val();
else
email = 'NULL';
word = $("#suggest-word").val();
pack = $("#suggest-pack").val();
lang = $("#suggest-lang").val();
var request = $.ajax({
url: "/ajax/suggestQuestion.php",
method: "POST",
data: {word: word, pack: pack, lang: lang, email: email}
});
$("#suggestQuestionModal .form-group").hide().children(':input').val('');
$('#suggestQuestionModal .form-group > :checkbox').prop('checked', false);
request.error(function(xhr,status,error) {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-danger').html("<?=$lg['suggest_error']?> <a class=\"alert-link reset-suggestion\"><br><?=$lg['try_again']?></a>").fadeIn('slow');
setTimeout(function() {
$('#suggestQuestionModal').modal('hide');
}, 10000);
});
});
request.success(function(result, status, xhr) {
if (result == "OK") {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-success').html("<?=$lg['suggest_success']?> <a class=\"alert-link reset-suggestion\"><br><?=$lg['suggest_add_another']?></a>").fadeIn('slow');
});
}
else {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-danger').html("<?=$lg['suggest_error_info']?> "+result+" <a class=\"alert-link reset-suggestion\"><br><?=$lg['try_again']?></a>").fadeIn('slow');
});
}
});
$("#suggestQuestionModal .modal-body").on('click', '.reset-suggestion', function() {
resetSuggestionModal();
});
}
});
showGroups();
function showGroups() {
$('#suggestQuestionModal .form-group > :input').on("change", function() {
if ($(this).parent().index() == currFormGroup) {
if (currFormGroup < maxFormGroups) {
currFormGroup++;
$('#suggestQuestionModal .form-group:eq('+currFormGroup+')').fadeIn('slow');
if (currFormGroup == 4) {
$('#suggest-email').rules('add', {required: true, email: true});
}
}
}
});
}
$('#suggestQuestionModal .form-group:eq(3) > :input').change(function() {
/*if ($(this).checked && $('#suggestQuestionModal .form-group:eq(4)').css('display') == 'none') {
alert("SHOW IT!");
$('#suggestQuestionModal .form-group:eq(4)').fadeIn('slow');
currFormGroup++;
alert(currFormGroup);
} */
if (!$(this).prop('checked') && $('#suggestQuestionModal .form-group:eq(4)').css('display') == 'block') {
$('#suggestQuestionModal .form-group:eq(4)').fadeOut('slow').children(':input').val('');
currFormGroup = currFormGroup - 1;
$('#suggest-email').rules('add', {required: false, email: false});
}
});
//}
AFAIK (I tried to debug it with alerts) something bad happens right before $('#suggestionSend').click closing bracket.
BTW. Yes, I know the code is really a piece of mess.
Any help - greatly appreciated.
You can try using Ajax done instead
request.done(function( result) {
$( "#element" ).fadeout() ;
});
I've got no idea of what happened.
Tried several times - no luck.
Then I decided to try with hide() and show() - still no luck.
After I changed it back to fadeIn() and fadeOut() - it suddenly works.
Some serious magic is going on...
EDIT: I've found it. I forgot that I moved fadeIn function outside of .form-group fadeOut, so from this:
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestLoading").fadeIn('fast');
$("#suggestionSend").attr('disabled', true);
});
I got this:
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestionSend").attr('disabled', true);
});
$("#suggestLoading").fadeIn('fast');
Previously, fadeIn function was being called 4 times (because of those .form-group elements).
Now it works great :)

Getting Checkbox Data

Sorry to ask yet another simple question but program can be hard and like they say never be afraid to ask.
What I am trying to do is get jquery to detect if the checkbox has been click or not then when the user clicks the send button it will then go to PHP to say if it has been checked or not.
I have got form data to process to PHP such as the text fields but the check fields doesn't seem to want to work.
I have tried googling I have find nothing on my end
Here's the code
$(document).ready(function () {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
login_username: $('#login-username').val(),
login_password: $('#login-password').val(),
remember_me: $('#remember_me').find(":checked").val()
}
}
$(":checkbox").click(function(){
$("#remember_me").text(this.value)
})
$('#login_content').hover(function() {
$(this).css("background-color", "transparent");
});
$('#login_content').mouseleave(function() {
$(this).css("background-color", "white");
});
$('.error').hover(function() {
$(this).css("background-color", "transparent");
});
$('.notice').hover(function() {
$(this).css("background-color", "transparent");
});
$('#login_content').mouseleave(function() {
$('.error').css("background-color", "#ffecec");
$('.notice').css("background-color", "#e3f7fc");
});
$(window).load(function(){
$('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded
// run every 7s
setInterval('cycleImages()',4000);
})
function loading(e) {
$('#login_try').show();
}
function hide_loading(e) {
$('#login_try').hide();
}
function success_message(e) {
$('#success_login').html("We're Just Signing You In");
}
function clearfields() {
$('#login-username').val(''); //Clear the user login id field
$('#login_password').val(''); //Clear the user login password field
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'check.php',
type: 'post',
error: function () {
//If your response from the server is a statuscode error. do this!!!
clearfields();
},
beforeSend: function () {
loading(e);
},
data: {
login_username: $('#login-username').val(),
login_password: $('#login-password').val(),
}, // get current values
success: function (data) {
//if your response is a plain text. (e.g incorrect username or password)
hide_loading(e);
if(data.indexOf("<b>Welcome Back</b>") > -1) {
hide_loading(e);
success_message(e);
}
if(data.indexOf("You're Already Signed In!") > -1) {
alert('This operation could not be proceeded');
}
$('#loading').fadeOut();
$('#content').hide();
$('#content').fadeIn(1000).html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function (e) {
if (e.keyCode == 13) {
var username = $('#login-username').val();
check(e);
}
});
$('#submit_login').click(function (e) {
if (e.keyCode != 13) {
check(e);
}
});
});
var isChecked = ($("#check_box_id").is(':checked')) ? 1 : 0;
//send this variable to the php file.

How to combine two jQuery functions into one?

I've following two functions in jQuery:
$(document).on('change','.states',function(){
//on change of select
});
$(document).on('click','.date_control',function(){
//on click of input .date_control
});
How to combine the above two functions into one function so that I can use it with my AJAX function which is as below:
$(function() {
$(".add_new_rebate").on("click", function(event) {
event.preventDefault();
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
});
});
If you have any other way than combining the above two function into one then also it will be fine. My requirement is to incorporate the code of these two functions into the above AJAX function as I'm generating the two HTML controls dynamically and I want to apply the jQuery classes to them. Thanks in advance.
JS:
function do_action(){
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
}
$(document).on('change','.states',function(){
//on change of select
do_action();
return false;
});
$(document).on('click','.date_control',function(){
//on click of input .date_control
do_action();
return false;
});
I'm assuming the reason why you asked the question is to avoid using the same code inside both events, this way, it's much cleaner. No repeating.
I am not that sure if I understood the point correctly, but I you can define a function withName () {}, so you can reference that function from withing the event handlers.
Here doStuff is called either on »change« or on »click«
function doStuff (e) {
//the stuff to do
}
$(document).on('change','.states', doStuff);
$(document).on('click','.date_control',doStuff);
I hope that is what you are asking for…
Please see this link:
How to combine two jQuery functions?
And the answer can answer your question:
you simply use the same selector for both your action and your confirm
function handler(event) {
event.preventDefault();
var manufacturer_id = $("#company_id").val();
/*if($.active > 0) { //or $.active
request_inprogress();
} else {*/
var next_rebate_no = $('.rebate_block').length + 1;
var rebate_no = $('.rebate_block').length + 1;
if ($('.rebate_block').length>0) {
rebate_no = rebate_no+1;
}
$('.add_new_rebate').attr('disabled','disabled');
//}
$.ajax({
type: "POST",
url: "add_rebate_by_product.php",
data: {'request_type':'ajax', 'op':'create_rebate', 'next_rebate_no':next_rebate_no, 'rebate_no':rebate_no, 'manufacturer_id':manufacturer_id},
beforeSend: function() {
$('.table-responsive').after("<img src='http://localhost/smart-rebate-web/web/img/ajax-loader.gif' class='load' alt='Loading...'>");
},
success: function(data) {
if(jQuery.trim(data)=="session_time_out") {
window.location.href = site_url+'admin/login.php?timeout=1';
} else {
$('.rebate_block').append(data);
$('.add_new_rebate').removeAttr('disabled');
}
$('.load').remove();
}
});
}
$(document).on('change','.states', handler);
$(document).on('click','.date_control', handler);
If I understood your requirement correctly, then the following should work:
$( '.states, .date_control' ).on( 'click change', function ( event ) {
if( ( event.type == 'change' && event.target.className == 'states' )
|| ( event.type == 'click' && event.target.className == 'date_control' ) ) {
//process event here
};
} );

loading my script using getScript

at first I'm loading all my js script in my header and it's all working properly. But I have one js file that need to be loaded inline/ load it in a certain page only.
this is the js file that I need to load
var myScroll,pullDownEl, pullDownOffset, generatedCount = 0;
function pullDownAction () {
setTimeout(function () {
var el, li, i;
el = document.getElementById('newlist');
if ( el.hasChildNodes() ) {
while ( el.childNodes.length >= 1 ) {
el.removeChild( el.firstChild );
}
}
for (i=0; i<6; i++) {
li = document.createElement('li');
li.innerText = 'Generated row ' + (++generatedCount);
el.insertBefore(li, el.childNodes[0]);
}
myScroll.refresh();
}, 1000);
}
function loaded() {
pullDownEl = document.getElementById('pullDown');
pullDownOffset = pullDownEl.offsetHeight;
myScroll = new iScroll('wrapper', {
//hideScrollbar: false,
//hScrollbar: false, vScrollbar: false, vScroll: false,
useTransition: true,
topOffset: pullDownOffset,
onRefresh: function () {
if (pullDownEl.className.match('loading')) {
pullDownEl.className = '';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
$('#pullDown').css('display', 'inherit');
$('#pullDown').css('display', 'none');
$('#thelist').css('display', 'none');
$('#newlist').css('display', 'inherit');
}
},
onScrollMove: function () {
if (this.y > 5 && !pullDownEl.className.match('flip')) {
pullDownEl.className = 'flip';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Release to refresh...';
$('#pullDown').css('display', 'inherit');
this.minScrollY = 0;
} else if (this.y < 5 && pullDownEl.className.match('flip')) {
pullDownEl.className = '';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
$('#pullDown').css('display', 'inherit');
this.minScrollY = -pullDownOffset;
}
},
onScrollEnd: function () {
if (pullDownEl.className.match('flip')) {
pullDownEl.className = 'loading';
pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Loading...';
pullDownAction();
}
}
});
setTimeout(function () { document.getElementById('wrapper').style.left = '0'; }, 800);
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
loading it with my other script in my header it works but now I'm using the jquery getScript. It loads the script (using firebug) but when I tried calling the functions inside my js file it give me a two errors
Cannot read property 'offsetHeight' of null
Cannot call method 'refresh' of undefined
This is how I call my js script using getScript
$(document).ready(function() {
$('.email').click(function (){
$.getScript("assets/js/scroll.js",function() {
pullDownAction();
loaded();
});
});
});
Help anyone
I know this may suggest more work than you want to do, but have you tried doing namespacing? I do not know if this works 100% (as i am not sure of the reasoning why that is not working for you), but have you tried this?
(function( PullDown, $, undefined ) {
//Private variables and this is a great way for minification, you will get the most out of it
var myScroll,pullDownEl, pullDownOffset, generatedCount = 0;
function pullDownAction () {
//... your stuff here
}
function loaded() {
//... more your stuff here
}
}(window.PullDown = window.PullDown || {}, jQuery) // avoids name space collision w/ jQuery
Now do the same things, but with this edit.
$(document).ready(function() {
$('.email').click(function (){
$.getScript("assets/js/scroll.js",function() {
window.PullDown.pullDownAction();
window.PullDown.loaded();
});
});
});
If i am not mistaken, or have bad copy and paste skills, this should work out just great!

Categories

Resources