ready state problem with ajax and jquery - javascript

i have the following problem. I'm trying to load a set of tab loading dinamically with jQuery.
When I get the new contents (via POST) the tabs() function abort and don't build the
tabs. I'm using this functions:
$(document).ready(function() {
var array_with_alias_id = $.getJSON("/getAliasForMatchAll/", null,
function (data){
array = data.aliases_id;
load(array);
});
$("#next_left").click(function(){next_left()});
//load(array_with_alias_id);
});
function next_left(){
if(j >= array.length-1){
var l = j
} else {
var l = j+=1;
}
$("#alias_id_left").val(list_left[l]);
$("#merge_alias_id_left").val(list_left[l]);
$.post("/visor/",{"alias_id":list_left[l],"position":"L"},
function(data){
$("#tabsL").html(data).ready(function(){
$("#tabsL").tabs();
});
});
}
I think that my problem is an ajax problem and i have read this [0],
but i can't give with the solution.
The function next_left() it works only one time. I think that the document for
this function is ready, but when i load the tabs it doesnt work
(i think that tab call the method abort, because if i see the html with firebug
it change, but not all).
Any clue?
[0]http://docs.jquery.com/Tutorials:AJAX_and_Events

Try replacing $("#next_left").click(function(){next_left()}); with:
$("#next_left").live('click', function(){next_left()});

People on IRC helped me.
I have now changed the function after the .POST to this:
function next_left(){
if(j >= array.length-1) {
var l = j
}
else {
var l = j+=1;
}
$("#alias_id_left").val(list_left[l]);
$("#merge_alias_id_left").val(list_left[l]);
$.post("/visor/",{"alias_id":list_left[l],"position":"L"},
function(data) {
$("#tabsL").html(data).tabs("destroy").tabs();
});
}
They correctly advised me that the ready function applies to the document and does not work how I used it. I hope the fixed code I posted here aids others.

Related

Is there any callback function after 'Friends List' loaded in cometchat?

I have integrated 'Embed Layout' comet chat on my site. Now I want to open particular friend chat on page load.
In the documentation, I've found below code to do the same. REF : Documentation Link
jqcc.cometchat.chatWith(user_id)
I have included in custom js from admin panel. However, it is showing below error in console
jqcc.cometchat.chatWith is not a function
But If I use same after friends list loaded from the console it is working fine.
How can I fix this issue?
Currently for time being I have fixed this issue by adding below code in custom js
var first_chat_loaded = false;
var first_chat = setInterval(function () {
try {
if (first_chat_loaded === false) {
// Function to get other user id defined in parent html page
var other_userid = parent.get_other_user_id();
jqcc.cometchat.chatWith(other_userid);
first_chat_loaded = true;
clear_first_load();
}
} catch (e) {
}
}, 1000);
function clear_first_load() {
clearInterval(first_chat);
}
Please let me know, If there is any proper way to do the same.
Kindly make use of this code snippet for the above mentioned issue
var checkfn = setInterval(
function(){
if(typeof jqcc.cometchat.chatWith == 'function'){
jqcc.cometchat.chatWith(user_id);
clearInterval(checkfn);
}
},
500);

Waiting for multiple iFrames to load before executing function

Forgive my naivety, this probably is quite obvious, I just can't see it now.
Please tell me what is wrong with the following code:
$('#iframe1').load(function(){
$('#iframe2').load(function(){
alert('loaded!');
});
});
The idea is to wait until both iframes have fully loaded, then alert "loaded" - of course this is a simplified example for the sake of stack.
The script sits in script tags at the end of the body of the html doc.
#Quertiy answer is perfectly fine, but not very jQuery-ish. It is hard-coded for 2 iframes only.
The beauty of jQuery is that you can make it work for the most number of people, with as little friction as possible.
I've advised a very simplistic plugin that does nearly what is present on that answer, but in a more open way. It not only works on iframes, but also on images, audio, video and whatever has a onload event!
Without further due, here's the code:
(function($){
$.fn.extend({allLoaded: function(fn){
if(!(fn instanceof Function))
{
throw new TypeError('fn must be a function');
}
var $elems = this;
var waiting = this.length;
var handler = function(){
--waiting;
if(!waiting)
{
setTimeout(fn.bind(window), 4);
}
};
return $elems.one('load.allLoaded', handler);
}});
})(window.jQuery);
It works by adding a load handler to every element in that selection. Since it is a plugin, you can use in whatever way you decide to use it.
Here's an example, that loads 30 random images:
//plugin code
(function($){
$.fn.extend({allLoaded: function(fn){
if(!(fn instanceof Function))
{
throw new TypeError('fn must be a function');
}
var $elems = this;
var waiting = this.length;
var handler = function(){
--waiting;
if(!waiting)
{
setTimeout(fn.bind(window), 4);
}
};
return $elems.one('load.allLoaded', handler);
}});
})(window.jQuery);
$(function(){
//generates the code for the 30 images
for(var i = 0, html = ''; i < 30; i++)
html += '<img data-src="http://lorempixel.com/g/400/200/?_=' + Math.random() + '">';
//stuffs the code into the body
$('#imgs').html(html);
//we select all images now
$('img')
.allLoaded(function(){
//runs when done
alert('loaded all')
})
.each(function(){
//the image URL is on a `data` attribute, to delay the loading
this.src = this.getAttribute('data-src')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id="imgs"></div>
Your problem, as said before many times, is that you have a load event attached to your iframe. That event is fired everytime the content change.
After that, you set a new event on #iframe2. When it's content changes, it will fire events left and right, above and beyound what you wish!
The best aproach is to keep track of which ones you loaded or not. After all have been loaded, you simply run the function.
The problem is that you're waiting until #iframe1 loads before you attach a handler for #iframe2 loading. So if #iframe2 loads first, you'll never get your callback.
Instead, watch the load event on both of them and track which ones you've seen:
var seen1 = false,
seen2 = false;
$('#iframe1, #iframe2').load(function(){
if (this.id == "iframe1") {
seen1 = true;
} else {
seen2 = true;
}
if (seen1 && seen2) {
alert('loaded!');
}
});
Why do you expect 2nd iframe to load after the first one?
~function () {
var loaded = 0;
$('#iframe1, #iframe2').load(function (){
if (++loaded === 2) {
alert('loaded!');
}
});
}()

jQuery each not functioning correctly

I have a slider with 10 slider elements. However, only 7 out of 10 elements are rendered, given my data structure contains 20 sets. The site is hosted here
The code in question
function populateCarousell(cdata) {
var x = 0; //debug
jQuery(".wslide-slides .wslide-slide").each(function() {
var single = cdata.shift();
var jcurrSlide = jQuery(this);
jcurrSlide.find(".wslide-caption-text").text(single.title);
jcurrSlide.find("a").attr('href', "https://carousell.com/p/" +single.id);
jcurrSlide.css({'background-image':Base64.decode('dXJs')+'('+single.primary_photo_full_url+')'});
jcurrSlide.css({'background-image':'contain'});
jcurrSlide.css({'background-position':'50% 50%'});
jcurrSlide.css({'background-repeat': 'no-repeat'});
x++; //debug
jcurrSlide.find(".wslide-slide-inner2").removeAttr('style').find("img").css({'display':'none'});
});
alert(x); //Outputs 7
}
which is activated by (to ensure page fully loaded)
function caroDataCallback(data) {
if(document.readyState != "complete" ) {
setTimeout(function() { caroDataCallback(data); }, 2000);
}
else{
populateCarousell(data);
}
}
Upon examination in Chrome, the results is
That's because your page is not fully loaded when you call populateCarousell(cdata) function in your javascript file. Try instead of using $(document).ready(), use the $(document).load() to make sure all the images are loaded before you initiate your carousel.
Update: Use $(window).on('load', function() { .. }); instead.
Hope this helps.

javascript working in localhost but not when hosted?

I'm trying to implement a simple image slider on my website but it doesn't seem to want to work. Nothing happens at all. Nothing I can think of has worked thus far so I thought I'd ask here. This is my code.
window.onload = function(){
image = document.getElementById("slideShow");
index = 0;
setInterval(slide, 3000);
};
function slide(){
index++;
if(index >= 6) {index = 0;}
path = "images/Slideshow/image"+index+".jpeg";
image.setAttribute("src",path);
}
window.onload is pretty cheesy because nobody seems to agree on what onload actually means.
i would recommend you use
document.addEventListener("DOMContentLoaded", function(){
// code
});
Another thing u should be aware of is slow loading. If the scripts gets loaded after the ready event has been fired then your code will never trigger.
A solution is wrapping the ready function is a seperate module.
var eventReady;
(function(){
var funcArr = [];
eventReady = function(func){
funcArr.push(func);
}
document.addEventListener("DOMContentLoaded", function(){
for(var i=0;i<funcArr.length;i++){
try{
funcArr[i]();
}
catch(e){
throw(e);
}
finally{
continue;
}
};
eventReady = function(func){
func();
}
});
})();
and then use the module like:
eventReady(function(){
// code
})

Jquery document.ready not triggered without alert

I'm facing this very weird issue that my function in document ready is not triggered, unless I put alert after the function. I found this out when I debug using the alert, and apparently everything was working fine. But when I removed the alert, function 'RaiseEvent' never get called.
Here's my HTML:
<script src="../Content/jquery.mobile-1.4.2/js/jquery.js"></script>
<script src="../Content/jquery.mobile-1.4.2/js/jquery.mobile-1.4.2.min.js"></script>
<script type="text/javascript" src="Scripts/hybrid.js"></script>
<script>
$(document).ready(function(){
//populate form
//alert('Calling POPULATE-FORM');
RaiseEvent('POPULATE-FORM');
//alert('After POPULATE-FORM');
});
</script>
The RaiseEvent function is retrieved from hybrid.js:
function RaiseEvent(eventName)
{
if (!eventName) eventName = '';
var qs = '';
var elms = document.getElementsByTagName('*');
for (var i = 0; i < elms.length; i++) {
if (elms[i].name) {
qs += (qs.length > 0 ? '&' : '') + encodeURIComponent(elms[i].name) + '=' + encodeURIComponent(elms[i].value);
}
if (elms[i].type == 'checkbox' && elms[i].checked)
qs += (qs.length > 0 ? '&' : '') +
'checked:' + encodeURIComponent(elms[i].name) + '=1';
}
location.href = 'xpostback:' + eventName + ':' + qs;
}
I've googled this issue and found few people facing this also Here but I followed his solution already to no avail.
Anyone facing the same issue or have any suggestions/advice what might go wrong?
I have some thoughts on your problem.
a) Callback function in ready()
From documentation handler is callback function which means that when DOM element is ready your function is beeing called. I suppose that is not the problem.
document.ready( handler );
b) Jquery.mobile
Fast googling told me that you could use different function. See pagecreated documentation.
$(document).on('pagecreated',function(){
RaiseEvent('POPULATE-FORM');
});
Also look here:
jQuery mobile $(document).ready equivalent
jQuery Mobile: document ready vs page events
c) Error in function RaiseEvent(eventName)
Even if your function works with alert this doesn't guarantee that you function is working properly. I had a lot of situations that in all modern browsers my code works but there was some bugs. Only Internet Explorer was so kind and throw me errors. I suggest running your code with JS debugger.
Summary
I would start from b) and then try to look at c). Good luck :)
Apparently there is another "document.ready" function in hybrid.js that caused inconsistent RaiseEvent calling. Probably because the asynchronous nature of Javascript, the RaiseEvent('POPULATE-FORM') get overlapped by the RaiseEvent('DOCUMENT-READY') in hybrid.js:
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
RaiseEvent("DOCUMENT_READY");
Init();
clearInterval(readyStateCheckInterval);
}
}, 50);
Credits to #Barmar for helping me debugging the isssue!

Categories

Resources