Error FB.XFBML.parse comment box facebook - javascript

Hi I have this javascript code:
$.fn.imagesLoaded = function () {
$imgs = this.find('img[src!=""]');
if (!$imgs.length) {return $.Deferred.resolve().promise();}
var dfds = [];
$imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.src = this.src;
});
return $.when.apply($,dfds);
}
var disc = function(div,of){
$(div).hide();
$('#loading').show();
var ajax = $.ajax({url : of, type : "GET", cache: false});
ajax
.done(function(response){
Commons.sorDone(div, response);
FB.XFBML.parse(document.getElementById('.fb-comments'));
twttr.widgets.load();
})
.fail(function(){
Commons.sorFail(div);
});
}
Commons = {
sorDone : function (div, response) {
$(div).html(response).imagesLoaded().then(function(){
$('#loading').hide();
$(div).show();
});
},
}
The code does is load content via a button in a div dynamically. While charging the content shows a gif preload.
Well, that content is no social buttons facebook and twitter and box of facebook comments also show that in order to be parsed with FB.XFBML.parse
So far so good, but the problem is that sometimes appear facebook comments and sometimes the empty space and comments are not displayed.
where it could be wrong?

I have solved just when placing below shows the div at the end.
For if someone helps. No longer fails, it will always spot the parse.
$.fn.imagesLoaded = function () {
$imgs = this.find('img[src!=""]');
if (!$imgs.length) {return $.Deferred.resolve().promise();}
var dfds = [];
$imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.src = this.src;
});
return $.when.apply($,dfds);
}
var disc = function(div,of){
$(div).hide();
$('#loading').show();
var ajax = $.ajax({url : of, type : "GET", cache: false});
ajax
.done(function(response){
Commons.sorDone(div, response);
})
.fail(function(){
Commons.sorFail(div);
});
}
Commons = {
sorDone : function (div, response) {
$(div).html(response).imagesLoaded().then(function(){
$('#loading').hide();
$(div).show();
FB.XFBML.parse(document.getElementById('.fb-comments'));
twttr.widgets.load();
});
},
}

Related

Javascript foreach loop calls ajax several times

So I am trying to create to do list with several boards. Each board have add item button. If I click add item button it opens modal where to insert task info. But if I click add item button several times and then insert info to modal and press save ajax fires as many times i clicked add item button. How can I prevent from that?
var addNewItems = document.querySelectorAll("#addNewItem");
var addNewSubmits = document.querySelectorAll("#listItemSave");
addNewItems.forEach(function(addNewItem) {
addNewItem.addEventListener("click", function(e) {
var newItemModal = this.nextElementSibling;
newItemModal.classList.toggle("hidden");
var addNewBtn = newItemModal.querySelector("#listItemSave");
//current board
var board = this.closest("div.list");
//current list
var list = board.querySelector(".todo--items");
addNewBtn.addEventListener ("click", function(e) {
//current board id
var boardId = board.dataset.boardid;
//current title
var title = newItemModal.querySelector("#listTitle");
var titleValue = title.value;
//current content
var content = newItemModal.querySelector("#listTextarea");
var contentValue = content.value;
$.ajax({
type: "POST",
url: "add.php",
data: { content: contentValue , title: titleValue , listid: boardId },
success: function(data, textStatus, jqXHR) {
$("#todoItems-" + id + "").append(data);
}
});
});
});
});
You could use a variable, lets say busy, to validate that an AJAX request isn't already on going.
You could set this variable in the beforeSend callback of AJAx and then updated it back to false in the finally callbac :
var addNewItems = document.querySelectorAll("#addNewItem");
var addNewSubmits = document.querySelectorAll("#listItemSave");
addNewItems.forEach(function (addNewItem) {
addNewItem.addEventListener("click", function (e) {
var newItemModal = this.nextElementSibling;
newItemModal.classList.toggle("hidden");
var addNewBtn = newItemModal.querySelector("#listItemSave");
//current board
var board = this.closest("div.list");
//current list
var list = board.querySelector(".todo--items");
var busy = false;
addNewBtn.addEventListener("click", function (e) {
//current board id
var boardId = board.dataset.boardid;
//current title
var title = newItemModal.querySelector("#listTitle");
var titleValue = title.value;
//current content
var content = newItemModal.querySelector("#listTextarea");
var contentValue = content.value;
if (!busy) {
$.ajax({
type: "POST",
url: "add.php",
beforeSend: () => {
busy = true;
}
data: {
content: contentValue,
title: titleValue,
listid: boardId
},
success: function (data, textStatus, jqXHR) {
$("#todoItems-" + id + "").append(data);
},
complete: () => {
busy = false;
}
});
}
});
});
});
This is a pretty simple solution but it works.
You can use addNewBtn.onclick = function () {} instead to overlap the previous listener in this case.
But it's not recommended to register listeners inside another listener. Try to move it out of there.

Why the click event will not working in jQuery?

I have a html and jQuery code in which there are two img dynamically created and after ajax I'm applying click events on the images but the click events not working. Means they show nothing. that the imae is clicked or not. I'm showing my code following:-
<div id="images">
<img id="image/5c07a4337c76881db6bf9a7f" src="data:image/jpeg;base64,/9j/4AA.....>
<img id="image/5c07a4337c76881db6bf9a7d" src="data:image/jpeg;base64,/9j/4AA.....>
</div>
$( document ).ready(function() {
$.ajax({
url: "/api/v1/get-all-upload-image?sortBy=date",
type: "GET",
success: function(response){
console.log(response);
$.ajax({
url : "/api/v1/base-strings",
type:"GET",
success:function(response){
console.log(response.response.data)
for (i= 0; i < response.response.data.length; i++){
console.log(response.response.data[i])
var base64_string = response.response.data[i].data;
var img = document.createElement("img");
img.setAttribute("id", "image/"+response.response.data[i].files_id);
img.setAttribute("onclick", "addListeners()");
// added `width` , `height` properties to `img` attributes
img.style.width ='340px';
img.style.height ='194px';
img.style.margin = '50px';
img.style.cursor = 'pointer';
img.src = "data:image/jpeg;base64," + base64_string;
var preview = document.getElementById("images");
preview.appendChild(img);
}
}
});
}
});
function addListeners () {
$('img[id^="image"]').on('click', function(){
var val = $(this).attr('id').split('/');
id= val[val.length - 1]
});
}
$('img[id^="image"]').click(function(){
alert("hello")
})
$('img[id^="image"]').on('click', function(){
var val = $(this).attr('id').split('/');
id= val[val.length - 1]
});
});
Error
Uncaught ReferenceError: addListeners is not defined
at HTMLImageElement.onclick
What is the problem with the code why it is not working?
Listen Just do it like I said. Paste the below code after your first ajax call:-
$('body').on('click','img', function(){
alert("I'm here");
});
Hope Works well :)

how to disable more than one times when a link was click by user in Angularjs

I have using ViewItems() function in An-click='VewItems(id)' to call a method in Controller in Angularjs but it seem not good yet because when user click more time my images which load from Model it will get more image or element which I append to a div much as the amount of clicking.
Here is my Function
$scope.ViewItems = function ($id) {
$('.modal-title').html('');
$('#bookimg').html('');
// Fetch an item from book list
if($id) {
id = $id;
$http({
method: 'GET',
url: url+id,
}).then(function successCallback(response) {
var http_code = response.data.s_respond;
$('<div id="loading"></div>').appendTo('body');
if (http_code === 200) {
SetErrors(http_code, 'OK');
var book_items = JSON.parse(response.data.data);
$('<h3>'+book_items.title+'</h3>').appendTo('.modal-title');
$('<img src=" '+book_items.image+' " width="100%" />').appendTo('#bookimg');
$('#myModal').modal({backdrop: 'static', keyboard: false});
} else {
SetErrors(http_code, 'warning');
}
}, function errorCallback(response) {
SetErrors(http_code, response.textStatus);
});
}
};
HTML
Maintain a variable isClicked and handle the callback accordingly.
var isClicked = false;
$scope.ViewItems = function ($id) {
if (isClicked) {
return;
}
isClicked = !isClicked;
...
}
Just create an array to solve this
var loadedIds = [];
$scope.ViewItems = function ($id) {
var index = loadedIds.indexOf($id);
if(index == -1){
loadedIds.push($id);
-------
}
};

How to hide a div after complete the ajax call,my code is given below ..in this code div hide before the refresh

How to hide a div after complete the ajax call,my code is given below... in this code div hide before the refresh
$(document).ready(function() {
$('#search-button').click(function() {
$('#imgLoader').show();
var request = $.ajax({
type: "GET",
url: 'response.php',
data: $('#search-form').serialize(),
success: function(response) {
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart');
$('#refcart').load(url + ' #shoppingCart');
$('#imgLoader').hide();
}
})
});
});
image loader hide before complete the refresh of two divs. Please help me
Take a look at http://api.jquery.com/load/
You can add a callback to the .load methods that will trigger once the element is fully loaded.
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
In your case, something like that:
$('#my_cart').load(url + ' #mycart', function () {
$('#imgLoader').hide();
);
A possible solution could be by using the complete parameter of load:
success: function(response) {
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart', function() {
$('#refcart').load(url + ' #shoppingCart', function() {
$('#imgLoader').hide();
});
});
}
Keep in mind, thats not the best solution, because the second load will be executed not until the completion of the first.
Edit:
I would suggest you to work with tokens:
success: function(response) {
var myCartLoaded = false;
var refCartLoaded = false;
var url = 'detail_page.php';
$('#my_cart').load(url + ' #mycart', function() {
myCartLoaded = true;
if(refCartLoaded) {
$('#imgLoader').hide();
myCartLoaded = false;
refCartLoaded = false;
}
});
$('#refcart').load(url + ' #shoppingCart', function() {
refCartLoaded = true;
if(myCartLoaded) {
$('#imgLoader').hide();
myCartLoaded = false;
refCartLoaded = false;
}
});
}
This way both load-functions will start at the same time and the one which stops last will trigger to hide your imageLoader.
You have more than one error in your code :
You make an ajax request to get search result, but you don't use the
response inside the success function. $().load is async, that
means you should wait the end of each $().load request before
hiding #imgLoader
The $().load is working like this
.load( url [, data ] [, complete ] )
And you should use promises to make it work.
$(document).ready(function() {
$('#search-button').click(function() {
$('#imgLoader').show();
// create the deffered instances
var myCartDeferred = $.Deferred();
var refCartDeffered = $.Deferred();
// $.ajax also return a deffered
var request = $.ajax({
type: "GET",
url: 'response.php',
data: $('#search-form').serialize(),
success: function(response) {
var url = 'detail_page.php';
$('#imgLoader').hide();
}
})
// Setup the chain of events
$.when(myCartDeferred, refCartDefferd, request).then(function() {
alert('done');
});
// start the load actions at the same time than the $.ajax and pass the deferred.resolve as complete param
$('#my_cart').load(url + ' #mycart', myCartDeferred.resolve);
$('#refcart').load(url + ' #shoppingCart', refCartDeffered.resolve);
});
});
jQuery .load returns jquery object making it inconvenient to wait for multiple loads to happen. You could add custom promiseToLoad method that returns a promise.
NB! Haven't tested this code.
$.fn.promiseToLoad = function(url, data) {
var dfd = $.Deferred(),
jquery = this;
jquery.load(url, data, function() {
if(dfd.state() === 'pending') {
dfd.resolveWith(jquery, jquery);
}
});
return dfd.promise();
}
and then
var myCart = $('#my_cart').promiseToLoad(url + ' #mycart'),
refCart = $('#refcart').promiseToLoad(url + ' #shoppingCart');
$.when(myCart, refCart).then(function() {
$('#imgLoader').hide();
});

Returning from JQuery 'get' when all images have loaded

I am using jquery get to load html onto my content div. The HTML I am loading contains some images and I am finding that my custom height calculation I am doing in javascript isn't working too well because the images are fully loaded when the loadHTML has returned.
var loadHTML = function(){
return $.get("javascripts/templates/" + templateType + ".html", function(text) {
$("#content").html(text);
});
};
Is there a way I can only return from loadHTML once all images have loaded? I tried to call and return load but this doesn't work
var loadHTML = function() {
return $.get("javascripts/templates/" + templateType + ".html", function(text) {
var content = $("#content").html(text);
return $('img', content).load();
})
};
Also, I am using Q promises in other parts of my application so is it possible to fix my problem using that.
ie. loadHTML.then(loadImages).then(doOtherStuff);
You can try to use a custom deferred object like below
var loadHTML = function () {
var deferred = $.Deferred();
$.get("javascripts/templates/" + templateType + ".html", function (html) {
var $html = $(html),
$imgs = $html.find('img'),
len = $imgs.length,
counter = 0;
$imgs.load(function () {
if (++counter == len) {
deferred.resolve();
}
});
$("#content").html($html);
});
return deferred.promise();
};
TD
var list = [];
for (var i = 0; i < 5; i++) {
list.push('<span><img src="//placehold.it/64&text=' + (i + 1) + '" /></span>');
}
var html = '<div>' + list.join('') + '</div>';
var loadHTML = function() {
var deferred = $.Deferred();
//using a timer to simulate ajax request
setTimeout(function() {
var $html = $(html),
$imgs = $html.find('img'),
len = $imgs.length,
counter = 0;
$imgs.load(function() {
if (++counter == len) {
deferred.resolve();
}
});
$("#content").html($html);
}, 500);
return deferred.promise();
};
loadHTML().done(function() {
$("#content").find('img').each(function() {
$(this).after(this.complete)
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content"></div>
Demo: Fiddle
Demo: Problem(Change the size of the image to see the problem)
Deleted my other answer because it was too wordy.
The reason your code is not working is because you are making an ajax request to a server, then returning from the function immediately. The page ploughs on with its scripting and probably finishes most if its work before that request comes back with your images.
You need to move your return to a place in your function you know is not going to process until the data comes back. You can use promises to do this:
var jqxhr = $.get( "example.php", function() {
alert( "request sent, images are loading" );
// DON'T PUT YOUR RETURN HERE,
//YOU WANT TO CALL IT WHEN THE ABOVE IS DONE
})
.done(function() {
alert( "the info is loaded" );
//put your html insert here to make sure the
//data is fully loaded before you manipulate it
//you could also call htmlresize here but that would be nesting.
//That shit gets complicated. Just call it after this function returns on success.
return
})
.fail(function() {
alert( "error" );
// its good to handle errors
return
})
if you dont want to hold up your whole page load to load some images you can do facny stuff like put the html resize and other dependent code on the jqxhr.sucess callback, so that other code gets read while your images come through. But that's complicated.

Categories

Resources