when fast cliking on like button getting unknown likes - javascript

i am working on project which have like unlike function look like facebook but i am getting stuck when i click multiple time at once on like button or unlike button then its work like firing and if i have 1 or 2 like and i click many time fast fast then my likes gone in -2 -1. how i solve this issue ? if when click many time always get perfect result. below my jquery script
$(document).ready(function () {
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
});
});
});

It is because of the async nature of ajax request.... when you click on the element continuously... the click event will get fired before the response from previous request come back and the link status is updated to next one
Case:
Assume the rel is unlike, then before the response came back again another click happens so the rel is not yet updated so you are sending another unlike request to server instead of a like request
Try below solution(Not Tested)
$(document).ready(function () {
var xhr;
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
}
//abort the previous request since we don't know the response order
if (xhr) {
xhr.abort();
}
xhr = $.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false
}).done(function (html) {
$('.spn' + ID).html(html);
}).always(function () {
xhr = undefined;
});
});
});

Set a variable, we'll call it stop and toggle it.
$(document).ready(function () {
var stop = false;
$(".like").click(function () {
if (!stop)
{
stop = true;
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
}).always(function() { stop = false; });
}
});
});

Related

Handling of click events in jQuery(For Like and Unlike button)

I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.
$(document).ready(function() {
$(".like").click(function() { //this part is working
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('like');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('liked');
$('a#' + item_id).html(data);
}
}
});
});
$(".liked").click(function() { //this part is not working
var item_id = $(this).attr("id");
console.log(item_id);
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('liked');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('like');
$('a#' + item_id).html(data);
}
}
});
});
});
$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.
If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:
$(document).ready(function() {
$('.like-toggle').click(function(event) {
if ($(event.target).hasClass('like') {
// Call your unlike code, replace like with liked.
} else {
// Call your like code, replace liked with like.
}
});
});
This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

Getting this in ajax result

im trying to make a script that changes P lines to input fields, let user edit them and then revert back to p lines after a check in an external php document through ajax. However the problem seems to be that I cant use this within the ajax part, it breaks the code. How can I solve that? Do I need to post the HTML?
$(document).ready(function () {
function changeshit(result, that) {
if (result == "success") {
$(that).closest('div').find('input').each(function () {
var el_naam = $(that).attr("name");
var el_id = $(that).attr("id");
var el_content = $(that).attr("value");
$(that).replaceWith("<p name='" + el_naam + "' id='" + el_id + "'>" + el_content + "</p>");
});
$(".editlink").replaceWith("Bewerken");
} else {
alert(result);
}
}
$(".editinv").on('click', 'a', function () {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if (edit_or_text == "edit") {
$(this).closest('div').find('p').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).text();
$(this).replaceWith("<input type='text' name='" + el_naam + "' id='" + el_id + "' value='" + el_content + "' />");
});
$(".editlink").replaceWith("Klaar");
} else if (edit_or_text == "done") {
var poststring = "";
$(this).closest('div').find('input').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).attr("value");
poststring = poststring + '' + el_naam + '=' + el_content + '&';
});
poststring = poststring + 'end=end'
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result, this) {
changeshit(result, this);
}
});
}
});
});
Yes, the common solutions is declare a var example self = this and use that variable
var self = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
changeshit(result, self);
}
});
}
In that way, the this context is save in the variable.
Try the following:
Right under $(".editinv").on('click', 'a', function () { add
$(".editinv").on('click', 'a', function () {
var element = this;
And then change this to:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result) {
changeshit(result, element);
}
});
That is if I am understanding correctly what you are trying to do
If you simply add:
context: this
to the $.ajax options then the success handler will automatically be called with the correct value of this, so you won't need the that parameter.
You'll then also no longer need the extra function wrapper around the success callback, so you can just use:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this, // propagate "this"
success: changeshit // just pass the func ref
});
There are a few ways you can achieve this
1) If you read the docs (jQuery.ajax) you'll see that you can supply a context to the ajax method
context
Type: PlainObject This object will be made the context of all Ajax-related callbacks. By default, the context is an object that
represents the ajax settings used in the call ($.ajaxSettings merged
with the settings passed to $.ajax).
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: function(result) {
// the context sent above would become the context of this function when called by jquery
changeshit(result, this);
}
});
Using it this way you could even do it like the bellow code
function changeshit (result) {
var $that = $(this);
if (result == "success") {
$that.closest('div')... // cool ha ?
};
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: changeshit
});
2) You can take advantage of closures ( read more here or search google ), so your code would become
var context = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
// here you can use any variable you declared before the call
changeshit(result, context);
}
});
As a side note, i would recommend you use variable/object caching, so declare var $this = $(this) at the top of the function and use it thruought your function, instead of calling $(this) each time you need it.

ajax success event doesn't work after being called

After searching here on SO and google, didn't find an answer to my problem.
The animation doesn't seem to trigger, tried a simple alert, didn't work either.
The function works as it is supposed (almost) as it does what i need to, excluding the success part.
Why isn't the success event being called?
$(function() {
$(".seguinte").click(function() {
var fnome = $('.fnome').val();
var fmorada = $('.fmorada').val();
var flocalidade = $('.flocalidade').val();
var fcodigopostal = $('.fcodigopostal').val();
var ftelemovel = $('.ftelemovel').val();
var femail = $('.femail').val();
var fnif = $('.fnif').val();
var fempresa = $('.fempresa').val();
var dataString = 'fnome='+ fnome + '&fmorada=' + fmorada + '&flocalidade=' + flocalidade + '&fcodigopostal=' + fcodigopostal + '&ftelemovel=' + ftelemovel + '&femail=' + femail + '&fnif=' + fnif + '&fempresa=' + fempresa;
$.ajax({
type: "GET",
url: "/ajaxload/editclient.php",
data: dataString,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
return false;
});
});
you are trying to pass query string in data it should be json data.
Does your method edit client has all the parameters you are passing?
A simple way to test this is doing the following:
change this line to be like this
url: "/ajaxload/editclient.php" + "?" + dataString;
and remove this line
data: dataString
The correct way of doing it should be, create a javascript object and send it in the data like so:
var sendData ={
fnome: $('.fnome').val(),
fmorada: $('.fmorada').val(),
flocalidade: $('.flocalidade').val(),
fcodigopostal: $('.fcodigopostal').val(),
ftelemovel: $('.ftelemovel').val(),
femail: $('.femail').val(),
fnif: $('.fnif').val(),
fempresa: $('.fempresa').val()
}
$.ajax({
url: "/ajaxload/editclient.php",
dataType: 'json',
data: sendData,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
Another thing shouldn't this be a post request?
Hope it helps

javascript alert in an if else statement not triggering

If the first part of the statement fails I am trying to send an alert. But I cannot figure out why the alert is not triggering. Yes, I have forced the statement to fail.
$("#btnSubmit").click(function (e)
{
if (<?php echo $browser; ?> >= 1)
{
var user = $("#ownerPost input").val();
var oid = <?php echo $Owner; ?>;
$.ajax(
{
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);
}
}
);
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}
else
{
alert("You must log in to follow");
}
}
);
Here is the output from view source:
The actual number is 56 and makes the statement true and that is correct. It is when the statement is false that it will not trigger the else and hence the alert.
If I place an alert right before the else it will show the alert because first part is true.
$("#btnSubmit").click(function (e)
{if (56 >= 1){
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data){
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);} });
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}else{alert("You must log in to follow");}});
I think you have a syntax error. I was going to suggest a try/catch, but that will not help with a syntax error. Please edit your question and put in the "view > page source" as the others have suggested. Also, can you use Firebug, or equivalent to view the console?
EDIT:
I do get the alert with this code. Note that I set browser to 0.
blah = function(e) {
if (0 >= 1) {
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type : 'POST',
url : 'follow.php',
data : "oid=" + oid,
dataType : 'json',
success : function(data) {
var id = data[0];
var name = data[1];
$('#output2')
.html("<b>id: </b>" + id + "<b> name: </b>" + name);
}
});
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
} else {
alert("You must log in to follow");
}
};
blah.call();

Categories

Resources