on jQuery .html() update, other functions stop working - javascript

I have certain "pages" on my website that are sortable. They also auto update to a database.
After my li list is sorted, a php page is called that re-orders the "pages" and then I call .html(data) to change the order of the pages that are displayed on the page.
After doing this, however, my auto update functions in my javascript stop working.
There is a #form1 that works before the sort takes place and the .html(data) is called. Once it is called, the previous #form1 get's removed and re-added to the page. This is when it stops working.
Does anyone know the reasoning for this?
My update script
$("#reportNav").sortable({
stop : function(event, ui){
var postData = $(this).sortable('serialize');
var url = "saveOrder.php";
$.ajax({
type: "POST",
url: url,
data: postData,
success: function(data) { $('#reportContainer').html(data); },
error: function(data) { $changesSaved.text("Could not re-order pages."); }
});
}
});
What stops working/stops being called
var timeoutId;
$('#form1').on('input propertychange change', function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
// Runs 1 second (1000 ms) after the last change
$("#form1").submit();
}, 1000);
});

Probably a case of over-writing your elements that has handlers bound, in which case you need event delegation:
$('#reportContainer').on('input propertychange change', '#form1', function() {

Related

JQuery & Ajax disable click

I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});

How to lock / set / block variable inside .on jquery

So, I have a jQuery AJAX call that gets data from the server (some text, some links).
Inside AJAX success callback function I got a .on that is bind to <a> that load for me next page and get me the text of the clicked link (let's say stackoverflow.com).
The problem starts here because in the newly loaded page I got anchors...
After every click on anchor links I got new .text() value.
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function(data){
$('.container').append(data);
$('.container').on('click', 'a', function(e){
e.preventDefault();
var clickLinkName = $(this).text();
console.log(clickLinkName);
$('.container').load($(this).attr('href'));
});
}
});
I would like to know how to lock clickLinkName variable. OR any other way to save only first hit.
I think this would do the trick:
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function(data) {
$(".container").append(data);
var clickLinkName; // Declared here.
$(".container").on("click", "a", function(e) {
e.preventDefault();
// If not initialized, initialize.
if(!clickLinkName) {
clickLinkName = $(this).text();
}
console.log(clickLinkName);
$(".container").load($(this).attr("href"));
});
}
});
That would save only the first value in the variable clickLinkName. This answers your question, but I'm sure there are better ways of doing this.

How to make setInterval run when browser tab is on focus?

I have created an Interval that runs on every 2 seconds, when the page loads. Now, when I move to other page, the interval is cleared (Please check the code). Now what I want is when I move to the same tab again, the interval should start again.
One thing I tried was that I wrote this whole code inside $(window).focus(//CODE) but the problem is that it doesn't run when the page is initially opened in any browser's tab.
How can solve this issue?
Here's my code:
var zzz= setInterval(anewFunc, 2000);
function anewFunc(){
$(document).ready(function(){
var chatattr=$(".chatwindow").css("visibility");
var chattitle=$("#hideid").text();
if(chatattr=="visible"){
$.ajax({
url: 'seen1.php',
type: 'post',
data: "ctitle="+chattitle,
success: function(result9){
},
error: function(){
}
});
}
$(window).blur(function(){
$.ajax({
url: 'session.php',
type: 'post',
success: function(result10){
// alert(result10);
},
error: function(){
}
});
clearInterval(zzz);
});
});
}
One thing I tried was that I wrote this whole code inside $(window).focus(//CODE) but the problem is that it doesn't run when the page is initially opened in any browser's tab.
Okay, the problem here is, the setInterval() doesn't execute at 0 seconds. It starts from 2 seconds only. So you need to make a small change:
Have the function separately.
Inside the ready event, start the timer, as well as run the function for the first time.
Remove the event handlers from the interval, or use just .one() to assign only once. You are repeatedly adding to the .blur() event of window.
Corrected Code:
function anewFunc() {
var chatattr = $(".chatwindow").css("visibility");
var chattitle = $("#hideid").text();
if (chatattr == "visible") {
$.ajax({
url: 'seen1.php',
type: 'post',
data: "ctitle=" + chattitle,
success: function(result9) {},
error: function() {}
});
}
$(window).one("blur", function() {
$.ajax({
url: 'session.php',
type: 'post',
success: function(result10) {
// alert(result10);
},
error: function() {}
});
clearInterval(zzz);
});
}
$(document).ready(function() {
var zzz = setInterval(anewFunc, 2000);
anewFunc();
});
Now what I want is when I move to the same tab again, the interval should start again.
You haven't started the setInterval() again.
$(document).ready(function () {
$(window).one("focus", function() {
var zzz = setInterval(anewFunc, 2000);
});
});

jquery mobile autocomplete , to show message while searching

I am using jquery mobile auto complete , Please see the demo at http://jsfiddle.net/Q8dBH/11/.
So whenever user press any letter,i need to show some message like "please wait."
So i added some code like below.But its showing only 1st time or 2nd time or not showing at all some times..How to show message whenever user types something until server responds back with data.
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
my full js is below.
$(document).on("pagecreate", ".ui-responsive-panel", function () {
$(document).on("click", "li", function () {
var text = $(this).text();
$(this).closest("ul").prev("form").find("input").val(text); });
$("#autocomplete").on("filterablebeforefilter", function (e, data) {
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
if (value && value.length >0) {
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
//$ul.listview("refresh");
$('.ui-responsive-panel').enhanceWithin();
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then(function (response) {
$.each(response, function (i, val) {
html += "<li data-role='collapsible' data-iconpos='right' data-shadow='false' data-corners='false'><h2>Birds</h2>" + val + "</li>";
});
$ul.html(html);
//$ul.listview("refresh");
//$ul.trigger("updatelayout");
$('.ui-responsive-panel').enhanceWithin();
});
}
});
});
Working example: http://jsfiddle.net/Gajotres/Q8dBH/12/
Now this is a complex question. If you want to show jQuery Mobile AJAX loader there's one prerequisite, AJAX call must take longer then 50 ms (jQuery Mobile dynamic content enhancement process time will not get into account). It works in jsFiddle example but it may not work in some faster environment.
You can use this code:
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
beforeSend: function() {
// This callback function will trigger before data is sent
setTimeout(function(){
$.mobile.loading('show'); // This will show ajax spinner
}, 1);
},
complete: function() {
// This callback function will trigger on data sent/received complete
setTimeout(function(){
$.mobile.loading('hide'); // This will hide ajax spinner
}, 1);
$.mobile.loading('hide'); // This will hide ajax spinner
},
data: {
q: $input.val()
}
})
beforeSend callback will trigger AJAX loader and complete callback will hide it. Of course this will work only if AJAX call lasts more then 50ms. Plus setTimeout is here because jQuery Mobile AJAX loader don't work correctly when used with web-kit browsers, it is a triggering workaround.

jquery click event

I have some jquery that looks like this,
$('.career_select .selectitems').click(function(){
var selectedCareer = $(this).attr('title');
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
}
});
});
My problem is that if the user keeps clicking then the .hfeed keeps getting data appended to it. How can I limit it so that it can only be clicked once?
Use the one function:
Attach a handler to an event for the elements. The handler is executed at most once per element
If you wanted the element to only be clicked once and then be re-enabled once the request finishes, you could:
A) Keep a state variable that updates if a request is currently in progress and exits at the top of the event if it is.
B) Use one, put your code inside a function, and rebind upon completion of request.
The second option would look like this:
function myClickEvent() {
var selectedCareer = $(this).attr('title');
var that = this;
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
},
complete: function() {
$(that).one('click', myClickEvent);
}
});
}
$('.career_select .selectitems').one('click', myClickEvent);
You can either use a global variable like
var added = false;
$('.career_select .selectitems').click(function(){
if(!added) {
// previous code here
added = true;
}
});
or use .one("click", function () { ... }) instead of the previous click function to execute the handler at most once per element. See http://api.jquery.com/one/ for more details.

Categories

Resources