Understanding Ajax and adding cart count - javascript

website: https://www.fermento24.com
If you add a product to the cart, it'll show you the recently added product, total and possibility to go to cart. What I wanted to add was a count of the sort, like: There are currently another 5 products in the cart.
I tried to use {{ cart.item_count }}, but since the popup works on Ajax it doesn't seem to update on time, only showing me at the first time how many products were in the cart (thus, incorrect informations).
How do I go and implement something like this? What follows under is a test I did based on other answers I found here, but that still didn't work.
<div class="loading-modal modal">{{ 'general.search.loading' | t }}</div>
<div class="newsletter-success-modal">
<div class="modal-overlay"></div>
<div class="ajax-modal-content">
<a class="close close-window btn" title="{{ 'general.password_page.close' | t }}">
<i class="fa fa-times"></i>
</a>
<i class="fa fa-check" aria-hidden="true"></i>
<span>{{ 'general.newsletter_form.mailing_list_success_message' | t }}</span>
</div>
</div>
<div class="ajax-error-modal modal">
<div class="modal-inner">
<div class="ajax-error-title">{{ 'general.search.error' | t }}</div>
<div class="ajax-error-message"></div>
</div>
</div>
<div class="ajax-success-modal modal">
<div class="overlay"></div>
<div class="content">
<div class="ajax-left">
<p class="added-to-cart info">{{ 'cart.general.added_to_cart' | t }}</p>
<p class="added-to-wishlist info">{{ 'products.wishlist.added_to_wishlist' | t }}</p>
<img class="ajax-product-image" alt="modal window" src="/" />
<div class="ajax-cart-desc">
<h3 class="ajax-product-title"></h3>
<span class="ajax_price"></span>
<p>{{ 'cart.general.qty' | t }}: <span class="ajax_qty"></span></p>
</div>
</div>
<div class="ajax-right">
<div>Totale nel carrello: <span class="ajax_cartTotal"></span><br>
<span class="cart-item-count"> </span>
</div>
<button class="btn continue-shopping" onclick="javascript:void(0)">{{ 'cart.general.continue_shopping' | t }}</button>
<div class="success-message added-to-cart"><i class="fa fa-shopping-cart"></i>{{ 'cart.general.view_cart' | t }} </div>
</div>
<i class="fa fa-times-circle"></i>
</div>
</div>
<script type="text/javascript">
$(function(){
var cartCount = {{ cart.item_count }};
$('.varients-item').on('click', function(){
var obj = $(this);
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: {
quantity: 1,
id: $(this).attr("data-variant")
},
dataType: 'json',
success: function (data) {
$.ajax({
type: 'GET',
dataType: 'json',
url: '/cart.json',
success: function(cart){
cartCount++;
$('.cart-item-count').html(cartCount);
}
});
}
});
});
});
</script>

You need to update the code and your JS code is looks like similar to demo code below:
$(function(){
$('.varients-item').on('click', function(){
var obj = $(this);
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: {
quantity: 1,
id: $(this).attr("data-variant")
},
dataType: 'json',
success: function (data) {
$.ajax({
type: 'GET',
dataType: 'json',
url: '/cart.js',
success: function(cart){
// once you get the data from AJAX API you need to get the latest count
let total = cart.item_count;
$('.cart-item-count').html(total);
}
});
}
});
});
});
Here is the reference for the cart.js over Shopify documentation.
Link

Related

Passing different URL parameters to AJAX function in Django

How to pass the different URL names to the javascript function. Here are my HTML and Javascript code.
{% for profile, g_name in group_list %}
<li class="contact">
<div class="wrap">
<img src="{{profile}}" alt="No image" />
<div class="meta">
<input type="hidden" id="myGroup" name="myGroup" value="{{g_name}}">
<button onclick="GetMessages()">
<p class="name">{{g_name}}</p>
</button>
</div>
</div>
</li>
{% endfor %}
<script>
function GetMessages() {
var myGroup = document.getElementById('myGroup').value;
$('.ajaxProgress').show();
$.ajax({
type: "GET",
url: "/getmsgs/"+myGroup,
success: function(response){
$("#display").empty();
...
},
error: function(response){
alert("No Data Found");
}
});
}
</script>
and this is my URL
path('getmsgs/<str:word>/', views.groupmsgs_ajax, name='groupmsgs_ajax'),
when I try the above method I am getting the first 'myGroup' id value. it is passing the first group name by default.
I am not able to call other group names.
Thank you for any help
That is because all input elements have the same id myGroup so document.getElementById('myGroup').value get always the first element value.
The following code changes should solve the issue given that g_id exists and is a string
{% for profile, g_name, g_id in group_list %}
<li class="contact">
<div class="wrap">
<img src="{{profile}}" alt="No image" />
<div class="meta">
<input type="hidden" id="{{g_id}}" name="{{g_id}}" value="{{g_name}}">
<button onclick="GetMessages({{g_id}})">
<p class="name">{{g_name}}</p>
</button>
</div>
</div>
</li>
{% endfor %}
<script>
function GetMessages(id) {
var myGroup = document.getElementById(id).value;
$('.ajaxProgress').show();
$.ajax({
type: "GET",
url: "/getmsgs/"+myGroup,
success: function(response){
$("#display").empty();
...
},
error: function(response){
alert("No Data Found");
}
});
}
</script>
Or pass the name directly to GetMessages function
{% for profile, g_name, g_id in group_list %}
<li class="contact">
<div class="wrap">
<img src="{{profile}}" alt="No image" />
<div class="meta">
<button onclick="GetMessages({{g_name}})">
<p class="name">{{g_name}}</p>
</button>
</div>
</div>
</li>
{% endfor %}
<script>
function GetMessages(myGroup) {
$('.ajaxProgress').show();
$.ajax({
type: "GET",
url: "/getmsgs/"+myGroup,
success: function(response){
$("#display").empty();
...
},
error: function(response){
alert("No Data Found");
}
});
}
</script>

How to identify multiple forms in one template?

I'm trying to implement a follower/following system in Django. In the template, all follow requests have a user and they all have user id's that can be displayed. The template is a profile page that contains several follow requests made by other users. I have created a separate form for each accept/decline and I want to uniquely identify each form so that I can submit that one and remove it subsequently.
<div class="col s12 l6 trending-panel container">
<h4>
Requests
</h4>
<div class="divider"></div>
{% for bond_request in bond_requests %}
{% if bond_request.accepted == False %}
<div>
<div class="row bond-request-row" id="{{bond_request.by_user.id}}">
<div class="col s6">
<a href="{% url 'accounts:profile' bond_request.by_user.username %}">
<div class="col s8">
<img class="profile-image-request" src="https://m.media-amazon.com/images/M/MV5BNjUxNDcwMTg4Ml5BMl5BanBnXkFtZTcwMjU4NDYyOA##._V1_.jpg" alt="">
</div>
<div class="col s4">
<h6 id="follower-username">
#{{bond_request.by_user}}
</h6>
</div>
</a>
</div>
<div class=" col s12 center accept-decline-margin">
<div class="col s12 l6">
<form action="accounts:accept_bond_request" method="POST" id="bond-request-accept-form">
<!-- <a href="#" id="bond-request-accept" class="green-text white btn">
<div>
<ion-icon name="add"></ion-icon>
<span>Accept</span>
</div>
</a> -->
<button id="bond-request-accept" class="green-text white btn" type="submit">Accept</button>
</form>
</div>
<div class="col s12 l6">
<a href="" class="grey-text white btn">
<div class="">
<ion-icon name="remove"></ion-icon>
<span>Ignore</span>
</div>
</a>
</div>
</div>
</div>
<!-- HERE -->
</div>
{% else %}
{% endif %}
<div class="divider">
</div>
{% endfor %}
</div>
$("#bond-request-accept-form").on('submit',function(){
// Cleans the username
// var each_bond_request = $();
var raw_follower_username = $("#follower-username").text().trim();
var follower_username = raw_follower_username.replace("#","");
console.log("Follower username: ",follower_username);
$.ajax({
type: "POST",
url: "/accounts/user/" + follower_username + "/accept_request",
data:{
"follower_username" : follower_username,
},
success: function(data){
console.log(data);
M.toast({html: follower_username + ' started following you',classes: 'green'}, );
},
error: function(data){
console.log("All error data: ",data);
M.toast({html: 'Failure',classes: 'red'}, );
},
});
});
You should create a standalone function to handle submit. And reference this function in each form you created.
function SubmitHandler (e) {
// Cleans the username
// var each_bond_request = $();
var raw_follower_username = $(e).find("#follower-username").text().trim();
var follower_username = raw_follower_username.replace("#","");
console.log("Follower username: ",follower_username);
$.ajax({
type: "POST",
url: "/accounts/user/" + follower_username + "/accept_request",
data:{
"follower_username" : follower_username,
},
success: function(data){
console.log(data);
M.toast({html: follower_username + ' started following you',classes: 'green'}, );
},
error: function(data){
console.log("All error data: ",data);
M.toast({html: 'Failure',classes: 'red'}, );
},
});
return false;
}
Then in your template:
...
<form id="bond-request-accept-form" onsubmit="SubmitHandler(this)">
...
Note the #follower-username should be nested within the form tag for jQuery to find the correct one.
First, I just want to say that I may be understanding your question wrong. If so, feel free to correct me.
If I am understanding this right, you have multiple copies of essentially the same form with slight variations depending on the user that is sending the request. Since IDs are meant to be unique and can cause issues in JavaScript if there are more than one instance of them, I would change the bond-request-accept-form to a class rather than an ID, and do something like this in JQuery:
$(".bond-request-accept-form").toArray().forEach(function(elem){
$(elem).on('submit', function(){
// Logic to perform when the form is submitted
});
});
Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.

Viima JQuery Comments - GetUsers(Pinged users) displaying incorrectly in partialview

References
jquery comments
The jquery comments documentation
this issue in github
Attachments
comments-data.js is test data : Download here
jquery-comments.js creates the whole comments system: Download here
jquery-comments.min.js if you require it: Download here
Description
I have a view with a list of "articles" with a "read more" button on each "article" in the list. When I click on the read more button a modal opens up with a partial view with the jquery comments in it. However, when I search for the pinged users (using the # sign), the list of users don't show by the textarea, but instead higher up in the modal (far from the textarea).
Below is an image, then below that is my code. You will see at the bottom of the image I have put the '#' sign and the list of users is displayed on the top, it should be by the textarea. It also seems that when I click on the articles lower in the list, the higher the list of users display when I push the '#' sign:
MVC View
Below is the part populating the "Articles" from where the Modal is being called from:
#{
int iGroupNameId = 0;
int iTotalArticles = 0;
foreach (var groupItems in Model.ArticleGroups)
{
iTotalArticles = Model.ArticlesList.Where(x => x.fkiGroupNameId == groupItems.pkiKnowledgeSharingCenterGroupsId).Count();
if (iTotalArticles > 0)
{
<div style="background: linear-gradient(#B5012E, darkred); margin: 10px; padding: 10px; font-weight: bold; color: white; text-transform: uppercase;">#groupItems.GroupName</div><div class="container" style="width:100%">
#if (groupItems.pkiKnowledgeSharingCenterGroupsId != iGroupNameId)
{
foreach (var item in Model.ArticlesList.Where(x => x.fkiGroupNameId == groupItems.pkiKnowledgeSharingCenterGroupsId))
{
<div class="row">
<div class="col-md-4">
#if (User.IsInRole("Administrator"))
{
<div class="pull-right">
<div class="btn-group">
<button class="btn dropdown-toggle btn-xs btn-info" data-toggle="dropdown">
<i class="fa fa-gear"></i> <i class="fa fa-caret-down"></i>
</button>
<ul class="dropdown-menu pull-right">
<li>
Edit
</li>
<li class="divider"></li>
<li>
Delete
</li>
</ul>
</div>
</div>
}
<img src="#item.ArticleImage" class="img-responsive" alt="img" style="width:350px;height:200px">
<ul class="list-inline padding-10">
<li>
<i class="fa fa-calendar"></i>
#item.DateTimeStamp.ToLongDateString()
</li>
<li>
<i class="fa fa-comments"></i>
#item.ArticleComments
</li>
<li>
<i class="fa fa-eye"></i>
#item.ArticleViews
</li>
</ul>
</div>
<div class="col-md-8 padding-left-0">
<h6 class="margin-top-0"> <span style="font-size:large">#item.Title</span><br><small class="font-xs"><i>Published by #item.User_FullName</i></small></h6>
<p>
#Html.Raw(item.Description)
</p>
#*<a class="btn btn-danger" href="#Url.Action("ShowArticleDetails", "ILearn", new { id = item.KnowledgeSharingArticlesId })">Read more</a>*#
<button type="button" onclick="showArticle('#item.KnowledgeSharingArticlesId')" class="btn btn-danger" data-target="#show-details-modal" data-toggle="modal">
Read more
</button>
</div>
</div>
<hr>
}
}
</div>
}
}
}
Modal
This is placed at the top of the page(Under the #model appname.ViewModels.VM):
<!--Loading Panel-->
<div id="loadingPanel" style="display: none;">
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-info" style="width: 100%">...LOADING...</div>
</div>
</div>
<!-- Show details modal-->
<div id="show-details-modal" class="modal fade" style="width:100%">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"></h4>
<div id="loadingPanelShowDetails" class="col-md-12 text-center" style="display: none;">
<br />
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-info" style="width: 100%">...LOADING...</div>
</div>
</div>
<div id="target-show-details">
</div>
</div>
</div>
</div>
</div>
Jquery Code
function showArticle(id) {
$("#target-show-details").html('');
$('#loadingPanelShowDetails').show();
$.ajax({
type: 'get',
url: '#Url.Action("ShowArticleDetails", "ILearn")',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
data: { "id": id },
success: function (result) {
$("#target-show-details").html(result);
$('#loadingPanelShowDetails').hide();
var saveComment = function (data) {
$(data.pings).each(function (index, id) {
var user = usersArray.filter(function (user) { return user.id == id })[0];
alert(user.fullname);
data.content = data.content.replace('##' + id, '##' + user.fullname);
});
return data;
}
$('#articlecomments-container').comments({
profilePictureURL: 'https://viima-app.s3.amazonaws.com/media/public/defaults/user-icon.png',
currentUserId: 1,
roundProfilePictures: true,
textareaRows: 1,
enableAttachments: true,
enableHashtags: true,
enablePinging: true,
getUsers: function (success, error) {
$.ajax({
type: 'get',
traditional: true,
url: '#Url.Action("GetPinnedUsers", "ILearn")',
success: function (usersArray) {
success(usersArray)
},
error: error
});
},
getComments: function (success, error) {
$.ajax({
type: 'get',
traditional: true,
data: { "id": id },
url: '#Url.Action("GetArticleComments", "ILearn")',
success: function (commentsArray) {
success(saveComment(commentsArray))
},
error: error
});
},
postComment: function (data, success, error) {
$.ajax({
type: 'post',
dataType: "json",
url: '#Url.Action("PostArticleComment", "ILearn")',
data: { "CVM": data, "articleId": id },
success: function (comment) {
success(comment);
},
error: error
});
},
putComment: function (data, success, error) {
$.ajax({
type: 'post',
dataType: "json",
url: '#Url.Action("PutArticleComment", "ILearn")',
data: { "CVM": data, "articleId": id },
success: function (comment) {
success(comment);
},
error: error
});
},
deleteComment: function (data, success, error) {
$.SmartMessageBox({
title: "Deleting Comment?",
content: "Are you sure that you want to delete this comment?",
buttons: '[No][Yes]'
}, function (ButtonPressed) {
if (ButtonPressed === "Yes") {
$.ajax({
type: 'post',
dataType: "json",
url: '#Url.Action("DeleteArticleComment", "ILearn")',
data: { "CVM": data, "articleId": id },
success: function (data) {
if (data.status === "usersuccess") {
$.smallBox({
title: "<strong>Comment Deleted</strong>",
content: "<i class='fa fa-clock-o'></i> <i>Comment was successfully deleted! <strong</strong></i>",
color: "#659265",
iconSmall: "fa fa-check fa-2x fadeInRight animated",
timeout: 4000
});
success();
} else {
success();
}
}
});
}
if (ButtonPressed === "No") {
$.smallBox({
title: "<strong>Comment not deleted</strong>",
content: "<i class='fa fa-clock-o'></i> <i>This comment has not been deleted.</i>",
color: "#C46A69",
iconSmall: "fa fa-times fa-2x fadeInRight animated",
timeout: 4000
});
}
});
e.preventDefault();
},
upvoteComment: function (data, success, error) {
if (data.user_has_upvoted) {
$.ajax({
type: 'post',
dataType: "json",
url: '#Url.Action("UpVoteArticleComment", "ILearn")',
data: { "CVM": data, "articleId": id },
success: function () {
success(data)
},
error: error
});
} else {
$.ajax({
type: 'post',
url: '#Url.Action("DeleteArticleCommentUpvote", "ILearn")',
data: { "commentId": data.id },
success: function () {
success(commentJSON)
},
error: error
});
}
},
uploadAttachments: function (commentArray, success, error) {
var responses = 0;
var successfulUploads = [];
var serverResponded = function () {
responses++;
// Check if all requests have finished
if (responses == commentArray.length) {
// Case: all failed
if (successfulUploads.length == 0) {
error();
// Case: some succeeded
} else {
success(successfulUploads)
}
}
}
$(commentArray).each(function (index, commentJSON) {
// Create form data
var formData = new FormData();
$(Object.keys(commentJSON)).each(function (index, key) {
var value = commentJSON[key];
if (value) formData.append(key, value);
});
formData.append('fkiKnowledgeSharingArticlesId', id);
$.ajax({
url: '#Url.Action("UploadToArticleComments", "ILearn")',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (commentJSON) {
successfulUploads.push(commentJSON);
serverResponded();
},
error: function (data) {
serverResponded();
},
});
});
}
});
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
}
});
}
MVC Partial View
#model Innovation_Cafe.Models.KnowledgeSharingArticles
<div class="col-lg-12">
<div class="margin-top-10">
<div style="text-align:center;border:solid;border-style:solid">
<img src="#Model.ArticleImage" class="img-responsive" alt="img" style="width:100%;">
</div>
<ul class="list-inline padding-10">
<li>
<i class="fa fa-calendar"></i>
#Model.DateTimeStamp.ToLongDateString()
</li>
<li>
<i class="fa fa-comments"></i>
#Model.ArticleComments
</li>
<li>
<i class="fa fa-eye"></i>
#Model.ArticleViews
</li>
</ul>
</div>
</div>
<div class="col-lg-12">
<h6 class="margin-top-0"> #Model.Title<br><small class="font-xs"><i>Published by #Model.User_FullName</i></small></h6>
<br />
<p>
#Html.Raw(Model.Description)
</p>
<p>
#if (Model.FileType == ".mp4")
{
<div style="text-align:center;border-style:solid">
<video controls width="100%">
<source src="#Model.FilePath" type="video/mp4" />
</video>
</div>
}
else
{
if (Model.FilePath !=null)
{
<p>Click here to view file: Click here</p>
}
}
</div>
<div class="col-md-12">
<p> </p>
<hr style="border:solid" />
</div>
<div class="row col-md-12">
<div class="col-md-12" id="articlecomments-container">
</div>
</div>
At the bottom of the partial view is this div where it is populated:
<div class="row col-md-12">
<div class="col-md-12" id="articlecomments-container">
</div>
</div>
EDIT
After spending quite some time running through the jquery-comments.js file, I found that displaying of the pinged users its happening here:
// CUSTOM CODE
// ========================================================================================================================================================================================
// Adjust vertical position
var top = parseInt(this.$el.css('top')) + self.options.scrollContainer.scrollTop();
this.$el.css('top', top);
This seems to be taking the css('top') of View, which causes the problem on the pinging of the users on the partialview.
The issue takes place rather because of your wrong bootstrap layout: you have to include all col into row, whereas in your example you use raw and col-md-12 for the same container.
After I included columns into row elements correctly everything started working the right way. In other words, just write the last section this way:
<div class="row">
<div class="col-md-12" id="articlecomments-container">
</div>
</div>
Please, take a look at an example of nesting in Bootstrap 4.
UPDATE
I've managed to reproduce the mistake thanks to your tip to draw numerous articles on the page. The issue is indeed because of scrolling, though the reason seems to be deeper in jquery.textcomplete.js in a function _fitToBottom (it takes into account the main window scroll but not of the embeded modal container). However, a faster approach I use instead of rectifying that elaborate peice of logic is exactly at the spot which you pointed to (instead of the last 2 rows you showed):
var topPoint = self.options.scrollContainer[0].offsetTop;
var scrolledWindow = self.options.scrollContainer.parents().filter(function () {
return this.scrollTop > 0;
})[0];
var spaceAvailable = $(window).height() - (topPoint - scrolledWindow.scrollTop);
var elHeight = this.$el.height();
this.$el.css('top', spaceAvailable > elHeight ? topPoint: topPoint - elHeight);
The logic is based on looking for the closest parent with scroll and then it measures whether the rest of the space is enough to render the dropdown to figure out its final position. It might slightly miss the pointer, but still works fine in spite of scrolling. I've tried it out in Chrome and Firefox. Hopefully, it will lead you to your own approach.

How do I update a specific span text in a repetitive list?

I want to update the text of class="count" in the span when the "Helpful" span class="upvote" is clicked. I use ajax to update the value in the database then I use the result to display in the count span.
However with my code below it updates all of them.
I have the below html
<div class="question">
<span class="upvote" data-id="1" data-cat="question"> Helpful <span class="count">2</span></span>
</div>
<div class="answers">
<span class="upvote" data-id="3" data-cat="answer"> Helpful <span class="count">15</span></span>
<span class="upvote" data-id="4" data-cat="answer"> Helpful <span class="count">66</span></span>
<span class="upvote" data-id="6" data-cat="answer"> Helpful <span class="count">0</span></span>
</div>
Here's my jquery
$('.upvote').click(function(event) {
$.ajax({
url: 'http://localhost/ask/upvote',
type: 'POST',
data: {
cat_id: $(this).data('id'),
category: $(this).data('cat'),
},
dataType: 'json',
success: function(json) {
$(".upvote span").text(json);
}
});
event.preventDefault();
});
You can save the reference of the upvote which was clicked
$('.upvote').click(function(event) {
let $clicked = $(this); //reference saved
$.ajax({
url: 'http://localhost/ask/upvote',
type: 'POST',
data: {
cat_id: $(this).data('id'),
category: $(this).data('cat'),
},
dataType: 'json',
success: function(json) {
$clicked.find( ".count" ).text(json); //observe changes in this line
}
});
event.preventDefault();
});

AJAX call botched by DOM Traversal

I am attempting to implement a Like / Dislike system with a counter. I am having problems with my AJAX call, more specifically when I am trying to change the HTML of selected elements in the view after passing values to the DB.
The element in question is .likeCount, a class with about a dozen or so siblings. If i simply use the selector $('.likeCount'), the AJAX call will actually successfully update the like count but it will do it for every instance of the class. If i attempt to use DOM traversal (.closest, this, .parent, etc) the like count does not update until I refresh the page.
the up and downvote carry a $('like') class.
$(document).ready(function()
{
$('.like').on('click', function(event)
{
postId = event.target.parentNode.parentNode.dataset['postid'];
var isLike = event.target.previousElementSibling == null;
$.ajax(
{
method: 'POST',
url: urlLike,
cache: false,
data: {isLike : isLike, postId : postId, _token : token},
success: function()
{
//first function working great
//(changes the like button to a disklike button and visa versa)
$.ajax(
{
method: 'POST',
url: urlCount,
cache: false,
data: {postId : postId, _token : token},
dataType: 'json',
async: true,
success: function(data)
{
var likeCount = event.target.parentNode.parentNode.childNodes[2].textContent;
$('likeCount').html(data["count"]);
console.log(data["count"]);
}
})
}
})
})
})
The console.log spits out the correct count every time.
How do I select the currently active likeCount without botching my AJAX call?
Here is the markup:
<div class="row posts">
<div class="col-md-6 col-md-offset-3">
<header><h3>Recent Posts:</h3></header>
#foreach($posts as $post)
#if (Storage::disk('local')->has($post->user->id . '.jpg'))
<div class="col-xs-2">
<img src="{{ route('account.image', ['filename' => $post->user->id . '.jpg']) }}" alt="" class="img-responsive">
</div>
#else
<div class="col-xs-2">
<img src="default.gif" alt="" class="img-responsive">
</div>
#endif
<article class="post col-xs-10" id="post" data-postid={{ $post->id }}>
<p class="post-body">{{ $post->body }}</p>
<div class="info">
Posted by {{ $post->user->name }} on {{ $post->created_at }}
</div>
<div class="likeCount">{{ $post->likes->where('like', '1')->count() }} other people liked this.</div>
<div class="interaction">
<a class="like btn upvote">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ? Auth::user()->likes()->where('post_id', $post->id)->first()->like == 1 ? 'You like this' : 'Like' : 'Like'}}</a> |
<a class="like btn downvote">{{ Auth::user()->likes()->where('post_id', $post->id)->first() ? Auth::user()->likes()->where('post_id', $post->id)->first()->like == 0 ? 'You dislike this' : 'Dislike' : 'Dislike'}}</a>
#if(Auth::user() == $post->user)
|
Edit |
Delete
#endif
</div>
</article>
#endforeach
<?php echo $posts->links(); ?>
</div>
</div>
The issue here is incorrect DOM Traversal.
var likeCount should be:
$(event.currentTarget.parentNode.parentNode.childNodes[5]);
Using 'event' simplifies things when multiple elements share a class name.

Categories

Resources