How to apply changes to the current class in jQuery? - javascript

I've read similar questions and tried different methods, but nothing seems to work. I have a Liking system. A heart image which switches between liked (filled heart icon) and unliked (Plain bordered heart icon).
The problem is, when I click on the like/heart button, all the other records' heart icon turns to liked state. The same goes with the like count. When I like a post, all the post's like count becomes the same.
Also, I'm running an AJAX request to get the likes count. When I try to output the likes and increment/decrement if they like/unlike, the output is weird. It goes to -1 or 01 etc.
This is my main.blade.php :
<span class="activityLikes">
<input type="hidden" class="activityIdHidden" value="{{ $activity->activity_id }}">
<a class="likeBtn">
#if(Auth::user()->hasLikedActivity($activity))
<img class="likeImg likeTrue" src="IMG/icons/likeTrue.png" alt="likes">
#else
<img class="likeImg likeFalse" src="IMG/icons/like.png" alt="likes">
#endif
</a><span class="likesCount">{{ $activity->likes->count() }}</span>
</span>
This is my main.js file :
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
$('.likeImg').attr('src', 'IMG/icons/like.png');
$('.likesCount').text(likeCount - 1);
} else if(data == "liked"){
$('.likeImg').attr('src', 'IMG/icons/likeTrue.png');
$('.likesCount').text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});

It is because you update every image that has the .likeImg class on the success event.
Can you try the following code ?
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
// element to update is `this` (the element that had been clicked)
var elementToUpdate = $(this).children('img');
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
elementToUpdate.attr('src', 'IMG/icons/like.png');
elementToUpdate.text(likeCount - 1);
} else if(data == "liked"){
elementToUpdate.attr('src', 'IMG/icons/likeTrue.png');
elementToUpdate.text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});

You should chain your Ajax calls, and get the count after updating the "like" status, like this:
function errHandler(e) {
console.log(JSON.stringify("Exception: " + e));
}
$('.likeBtn').on('click', function(e){
var activityId = +$(this).siblings(".activityIdHidden").val(),
$img = $("img", this),
$likes = $(this).siblings(".likesCount");
e.preventDefault();
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
error: errHandler
}).then(function(data){
$img.attr('src', data === "deleted" ? 'IMG/icons/like.png' : 'IMG/icons/likeTrue.png');
return $.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
error: errHandler
});
}).then(function(data){
$likes.text(data);
});
});

Related

reCAPTCHA: Multiple callbacks doesn't work

I'm creating a login and signup system and to avoid bots, i'm using google recaptcha and i'm trying to use multiple callbacks to send form data to the server via ajax request and this appeared in console:
ReCAPTCHA couldn't find user-provided function: [object Object]
This is the code (the problem is in the line 4):
$(window).on('load',function(){
grecaptcha.render('recaptcha', {
'sitekey' : '6LcFrN8cAAAAAMr2P3Nkvm7fDFzIykf30QykYlga',
'callback' : {onSubmitLogin, onSubmitSignUp},
'size' : 'invisible'
});
});
//Login
$('#login').submit(function (e) {
e.preventDefault();
grecaptcha.execute();
}
);
function onSubmitLogin(token){
var formEmail = $('#email-login').val();
var formPasswd = $('#password-login').val();
var reCaptchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'account.php?action=login',
method: 'POST',
data: {formEmail, formPasswd, reCaptchaResponse},
dataType: 'json',
beforeSend: function() { $('#loading').fadeIn("slow"); },
complete: function() {
$('#loading').fadeOut("slow");
grecaptcha.reset();
},
success: function(response){
if(response.status == 'error'){
$('#alert-container').prepend('<div class="alert ' + response.status + ' showAlert"><div class="alert-content"><i class="fas fa-exclamation-circle"></i><p>' + response.message + '</p></div><button class="alert-close"><i class="fas fa-times"></i></button></div>');
}else if(response.status == 'success'){
window.location = "dashboard";
}
}
})
};
//SignUp
$('#signup').submit(function (e) {
e.preventDefault();
grecaptcha.execute();
}
);
function onSubmitSignUp(token){
var formEmail = $('#email-sign-up').val();
var formPasswd = $('#password-sign-up').val();
var formConfirmPasswd = $('#confirm-password-sign-up').val();
var reCaptchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'account.php?action=create',
method: 'POST',
data: {formEmail, formPasswd, formConfirmPasswd, reCaptchaResponse},
dataType: 'json',
beforeSend: function() { $('#loading').fadeIn("slow"); },
complete: function() {
$('#loading').fadeOut("slow");
grecaptcha.reset();
},
success: function(response){
$('#alert-container').prepend('<div class="alert ' + response.status + ' showAlert"><div class="alert-content"><i class="fas fa-exclamation-circle"></i><p>' + response.message + '</p></div><button class="alert-close"><i class="fas fa-times"></i></button></div>');
}
})
};
why don't you do something like this instead?
grecaptcha.render('recaptcha', {
'sitekey' : '6LcFrN8cAAAAAMr2P3Nkvm7fDFzIykf30QykYlga',
'callback' : () => {
onSubmitLogin();
onSubmitSignUp();
},
'size' : 'invisible'
});

Delete data by ajax in laravel

I'm trying to delete items by ajax, so far i can get each item id but somehow when i click on delete button it just getting first item id.
code
controller
public function delqtydisc(Request $request,$id)
{
$dele = QtyDiscount::find($id)->delete();
return response()->json($dele);
}
route
Route::post('/delqtydisc/{id}', 'QtyDiscountController#delqtydisc')->name('delqtydisc');
script
<script>
$(document).ready(function() {
$("#addnewqtydiscmsgsave").click(function(e){
e.preventDefault();
//this adds new items to database (no issue here)
$.ajax({
type: "post",
url: "{{ url('admin/addnewqtydisc') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'amount': $('#amount').val(),
'min': $('.min').val(),
'max': $('.max').val(),
},
success: function (data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>');
var $tr = $('<tr/>');
$tr.append($('<td/>').html(data.min));
$tr.append($('<td/>').html(data.max));
$tr.append($('<td/>').html(data.amount));
// This adds delete button to my table
$tr.append($('<td/>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
$('.list-order tr:last').before($tr);
$("#min").val('');
$("#max").val('');
$("#amount").val('');
// From this part delete function adds
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $('.qtyitemid').data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
}
});
});
// end of delete fuction
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
PS: I commented each part of my JavaScript code that I thought should
bring your attention
// This adds delete button to my table and // From this part delete function adds
Error
when I hit delete button I get 3 results (if i have 3 inputs) in my network, first one return true the other 2 return
"message": "Call to a member function delete() on null",
Any idea?
Update
with code below my problem is solved some how, the only issue is remained is that i still get my row id's multiple. e.g. when i delete id=1 network show it one time but when after that i delete id=2 network shows two times id=2
<script>
$(document).ready(function() {
$("#addnewqtydiscmsgsave").click(function(e){
e.preventDefault();
$.ajax({
type: "post",
url: "{{ url('admin/addnewqtydisc') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'amount': $('#amount').val(),
'min': $('.min').val(),
'max': $('.max').val(),
},
success: function (data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>').fadeIn().delay(4000).fadeOut();
var $tr = $("<tr id='" + data.id + "'>");
$tr.append($('<td>').html(data.min));
$tr.append($('<td>').html(data.max));
$tr.append($('<td>').html(data.amount));
$tr.append($('<td>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
$('.list-order tr:last').before($tr);
$("#min").val('');
$("#max").val('');
$("#amount").val('');
//delete item
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $(this).data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>').fadeIn().delay(3000).fadeOut();
$('table tr#'+QtyitemID+'').remove();
}
});
});
//
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
PS: basically most of my problem is solved i'm just looking for answer
to avoid this multiple id in network.
The error occurred in your qtyitemid on click event. Specifically this line: var QtyitemID = $('.qtyitemid').data('id');
This JS code will always return the data of the first qtyitemid class. You must use the keyword this to determine what element is clicked. This code hopefully fix the problem:
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $(this).data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
}
});
});

Ajax/JS Does not go

The script is nothing back what this could be?
Here a link to the page Test Link
$(document).ready(function() {
// Anmeldung des Namens
$("#startfrom").submit(function() {
if($("#yourname").val() == "") {
$("#response").html("Bitte gebe einen Namen an!");
} else {
name = $("#yourname").val();
$("#submit").attr("disabled", "disabled");
$("#response").html("Lade...");
$.ajax({
type: "POST",
url: "chat.php"
data: "name=" + name
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
}
return false;
});
});
The code is intended to provide an issue who was entering no name.
The problem is you missed commas at the end of these lines:
url: "chat.php"
data: "name=" + name
These both lines need , in the end. They are objects. Corrected code:
$.ajax({
type: "POST",
url: "chat.php",
data: "name=" + name,
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
The other mistake is: Change your form id: Your form id is 'startform' not 'startfrom'.
Update
Hope this above one helps you.
Works for me after putting the comma:
Your form id is 'startform' and you wrote is 'startfrom'.
So, first of all correct you id name which you wrote in jquery and then try it.
After this if you got any error then try this code :
$(document).ready(function() {
// Anmeldung des Namens
$("#startform").submit(function() {
if($("#yourname").val() == "") {
$("#response").html("Bitte gebe einen Namen an!");
} else {
var name = $("#yourname").val();
$("#submit").attr("disabled", "disabled");
$("#response").html("Lade...");
$.ajax({
type: "POST",
url: "chat.php",
data: { name: name},
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
}
return false;
});
});
I hope you will get your solution.

Ajax call not succeeding after function call

I am attempting to load dynamic data based on the specific URI segment thats on the page.
Heres my Javascript:
$(document).ready(function() {
$(function() {
load_custom_topics();
});
$('#topics_form').submit(function() {
var topic = document.getElementById('topics_filter').value
$.ajax({
type: "POST",
url: 'ajax/update_session_topic',
dataType: 'json',
data: { topic: topic },
success: function(){
load_custom_topics()
}
});
return false;
});
function load_custom_topics(){
$.ajax({
type: "POST",
url: 'ajax/load_custom_topics',
dataType: 'json',
data: {},
success: function (html) {
$('div.topics_filter').html(html['content']);
get_threads();
}
});
}
function get_threads(){
var page = document.getElementById('page').value
$.ajax({
type: "POST",
url: 'ajax/get_threads',
dataType: 'json',
data: {page: page},
success: function (html) {
$('div#thread_list').html(html['content']);
}
});
}
});
So, as you can see, on page load, it kicks off load_custom_topics which runs just fine. Its then supposed to call get_threads(). This is where the thing stops, and I get no data.
Get_threads()
public function get_threads()
{
$session = $this->session->userdata('active_topic');
if ($this->input->post('page') == '1')
{
$data['list'] = $this->right_model->thread_list_all();
$data['test'] = "all";
} else {
$data['list'] = $this->right_model->thread_list_other($session);
$data['test'] = "not all";
}
if ($data['list'] == FALSE)
{
$content = "no hits";
} else {
$content = $this->load->view('right/thread_list', $data, TRUE);
}
$data['content'] = $content;
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
While I create the 'page' dynamically, the HTML outputs to this:
<div name="page" value="1"></div>
Any reason why get_threads() is not running?
This does not have an ID. It has a name.
<div name="page" value="1"></div>
This means that your request for getElementById is failing. So this line of code should be showing a TypeError in your console.
var page = document.getElementById('page').value

jquery ajax call execute once function after complete

I am in mobile app. I use ajax calls to receive data from webserver with this code:
$.ajax({
url: 'http://www.xxxxxxxxxxxx',
data: {name: 'Chad'},
dataType: 'jsonp',
success: function(data){
$.each(data.posts, function(i,post){
$.mobile.notesdb.transaction(function(t) {
t.executeSql('INSERT into bill (barcode, buildingcode, buildingaddress, flatname, flatdescription, entryseason, period, amount, pastpayments, todaypayments, receiptno) VALUES (?,?,?,?,?,?,?,?,?,?,?);',
[post.Id, post.Code, post.Address, post.Name, post.Description, post.EntrySeason, post.Period, post.Revenue, post.PastPayments, post.todaypayments, post.receiptno],
function(){
bill = 1;
$('#mycontent').append("bill - OK");
}
);
});
});
}
});
I want bill - OK displayed only once after all data inserted into sqlite.
try this:
success: function(data){
var count = data.posts.length;
$.each(data.posts, function(i,post){
$.mobile.notesdb.transaction(function(t) {
t.executeSql(<...>,
function() {
bill = 1;
if (--count == 0) {
$('#mycontent').append("bill - OK");
}
}
);
});
});
}
try to add:
$.ajax({
url: 'http://www.xxxxxxxxxxxx',
data: {name: 'Chad'},
dataType: 'jsonp',
async: false, //this line here
//...
EDIT
OK, what about:
$.each(data.posts, function(i,post){
//rest of stuff
});
$('#mycontent').append("bill - OK"); //this line outside the each() call

Categories