Ajax redirecting when it is not supposed to [duplicate] - javascript

This question already has answers here:
jQuery ID selector works only for the first element
(7 answers)
Closed 6 years ago.
I've implemented a program something like a shopping cart where you would add products to the cart. I'm using ajax make the page dynamic so multiple products can be added to the cart without a page reload. For some reason, the first product in the list can be added correctly while the rest of products alway redirects to the controller url when it isn't supposed to.
View Code
<section class="grid grid--loading" id="portfoliolist">
<!-- Loader -->
<img class="grid__loader" src="~/Images/grid.svg" width="60" alt="Loader image" />
<!-- Grid sizer for a fluid Isotope (Masonry) layout -->
<div class="grid__sizer"></div>
<!-- Grid items -->
#foreach (var item in Model.ProductsList)
{
var pricetag = "pricegroup3";
if (item.Price <= 300)
{
pricetag = "pricegroup1";
}
else if (item.Price > 300 && item.Price <= 500)
{
pricetag = "pricegroup2";
}
<div class="grid__item #item.Type #pricetag">
<div class="slider">
#foreach (var image in Model.ProductImagesList.Where(m=>m.ProductID == item.Id))
{
<div class="slider__item"><img src="~/Images/Products/#image.Image" /></div>
}
</div>
<div class="meta">
<h3 class="meta__title">#item.Name</h3>
<span class="meta__brand">#item.Brand</span>
<span class="meta__price">R #item.Price</span>
</div>
<a class="action action--button action--buy" href="#Url.Action("AddToPlatform", "ProductPlatforms", new { ProdID = item.Id })" id="platformAdd" data-value="#item.Id"><i class="fa fa-shopping-cart"></i><span class="text-hidden">Add to Platform</span></a>
</div>
}
</section>
The last tag is what will be clicked on to add the product to the cart.
Script -Ajax
$("#platformAdd").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("href"),
success: toastr["success"]("Product added to Platform")
});
});
Controller function
public void AddToPlatform(int ProdID)
{
var currUser = User.Identity.GetUserId();
DateTime now = DateTime.Now;
var exists = ProductExists(ProdID);
if (exists == false)
{
ProductPlatform prodPlatform = new ProductPlatform()
{
ProductID = ProdID,
UserID = currUser,
ViewedStatus = false,
DateAdded = now
};
db.ProductPlatforms.Add(prodPlatform);
db.SaveChanges();
}
}
The ajax script function would call the controller function which will add the product to the cart. Since there are no redirects I can't seem to figure out why the ajax call redirects to the tag "href".
Thanks for any help!

You need to use class instead of id because ids are always unique.
$(".lnkAddProduct").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("href"),
success: function(){alert("ADDED");}
});
});

Related

Loading category tags with load more button

I am new to jQuery. I have implemented a "load more" button on my blog app using jQuery, however the categories tags doesn't get displayed on the html when I click on that button.
Everything works fine so far, I can't just display the tags on the post card, it keeps returning undefined.
Note: I'm getting my categories from a many to many field relationship
Here are my views:
def home(request):
post = BlogPost.objects.all()[0:5]
total_post = BlogPost.objects.count()
context = {'post': post, 'total_post':total_post}
return render(request,'blog/home.html', context)
def load_more(request):
# get total items currently being displayed
total_item = int(request.GET.get('total_item'))
# amount of additional posts to be displayed when i click on load more
limit = 3
posts = list(BlogPost.objects.values()[total_item:total_item+limit])
print(BlogPost.objects.all())
data = {
'posts':posts,
}
return JsonResponse(data=data)
Template:
<div class="blogpost-container">
<div class="blogposts" id="blog-content">
{% for post in post %}
<div class="post">
<img id="img-src" src="{{post.image.url}} " image-url="{{post.image.url}}" alt="">
<p><strong>{{post.title}}</strong></p>
{% for category in post.category.all%}
<h3>{{category}}</h3>
{%endfor%}
<a id="post-detail-link" href="{% url 'detail' post.id %}" detail-url="{% url 'detail' post.id %}"><h2>{{post.summary}}</h2></a>
</div>
{%endfor%}
</div>
</div>
<div class="add-more" data-url='{% url "load_more" %}'id="add-btn">
<button type="button" class="more-content">load more</button>
</div>
<div class="alert no-more-data" role="alert" id="alert">
No more post to load!!!
</div>
{{total_post|json_script:"json-total"}}
JS file:
const loadBtn = document.getElementById('add-btn')
const total_post = JSON.parse(document.getElementById('json-total').textContent);
const alert = document.getElementById('alert')
function loadmorePost(){
const content_container = document.getElementById('blog-content');
var _current_item =$('.post').length;
$.ajax({
url:$('.add-more').attr('data-url'),
type:'GET',
data:{
'total_item':_current_item
},
beforeSend:function(){
alert.classList.add('no-more-data')
},
success:function(response){
const data = response.posts
alert.classList.add('no-more-data')
data.forEach(posts => {
const imageurl = 'media/'+posts.image
const detailurl = 'post/'+posts.id;
const category = posts.category;
content_container.innerHTML +=`<div class="post" id=${posts.id}>
<img id="img-src" src=${imageurl} image-url="{{post.image.url}alt="">
<p><strong>${posts.title}</strong></p>
<h3>${category}</h3>
<a id="post-detail-link" href=${detailurl}><h2>${posts.summary}</h2></a>
</div>`
})
if (_current_item == total_post){
alert.classList.remove('no-more-data')
loadBtn.classList.add('no-more-data')
}
else{ loadBtn.classList.remove('no-more-data')
alert.classList.add('no-more-data')
}
},
error:function(err){
console.log(err);
},
});
};
loadBtn.addEventListener('click', () => {
loadmorePost()
});

Ajax search doesn't work the second time (ASP.NET MVC)

I have a problem changing items after searching.
I looked at similar threads but found no solution there :(
It looks like the first time the page loads well - the first time the entire Index.cshtml page is loaded which contains a collection of books in the selected category.
There is a search engine on the page - after searching for "manual" - ajax correctly replaces elements with those containing "manual" in the name.
Then when I enter something into the search engine a second time (for example "exercises") - the content of the page does not change any more.
I tried to debug and I see that new items are correctly downloaded from the database - the condition "if (Request.IsAjaxRequest ())" is true and the items are passed to partial view - there the "foreach" loop goes through them. Unfortunately, after _Partial, nothing happens.
I can't find a mistake - the strangest thing is that the first ajax call works fine - only the second (and subsequent) bad.
CatalogController.cs
public ActionResult Index(string categoryName = null, string searchQuery = null)
{
if (categoryName == null)
categoryName = (db.Categories.Find(1)).Name;
var category = db.Categories.Include("Books").Where(x => x.Name.ToLower() == categoryName).Single();
var books = category.Books.Where(x => (searchQuery == null || x.Title.ToLower().Contains(searchQuery.ToLower()) || x.SubTitle.ToLower().Contains(searchQuery.ToLower()) || x.Level.ToLower().Contains(searchQuery.ToLower())) && !x.Inaccessible);
if (Request.IsAjaxRequest())
return PartialView("_PartialBooksList", books);
else
return View(books);
}
Index.cshtml
<form class="o-search-form" id="search-form" method="get" data-ajax="true" data-ajax-target="#booksList">
<input class="o-search-input" id="search-filter" type="search" name="searchQuery" data-autocomplete-source="#Url.Action("SearchTips")" placeholder="Search" />
<input class="o-search-submit" type="submit" value="" />
</form>
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
#section Scripts
{
<script src="~/Scripts/jquery-3.5.0.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
var setupAutoComplete = function () {
var $input = $(this);
var options =
{
source: $input.attr("data-autocomplete-source"),
select: function (event, ui) {
$input = $(this);
$input.val(ui.item.label);
var $form = $input.parents("form:first");
$form.submit();
}
};
$input.autocomplete(options);
};
var ajaxSubmit = function () {
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
$.ajax(settings).done(function (result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
});
return false;
};
$("#search-filter").each(setupAutoComplete);
$("#search-form").submit(ajaxSubmit);
});
</script>
}
_PartialBooksList
#model IEnumerable<ImpressDev.Models.Book>
#using ImpressDev.Infrastructure
<div class="row">
#foreach (var book in Model)
{
<div class="col-12 col-xl-4">
<a class="o-shop-link" href="#Url.Action("Details", "Catalog", new { bookId = book.BookId })">
<div class="o-shop-item">
<img class="o-shop-img" src="#Url.BookPhotoSourcePath(book.PhotoSource)" />
<div class="o-shop-text">
<h2>#book.Title</h2>
<h6>#book.SubTitle - #book.Level - <b>#book.Price zł.</b></h6>
+ Add to cart
</div>
</div>
</a>
</div>
}
</div>
Please help
I am not sure if this is the case, but try to change this code:
$($targetElement).replaceWith($newContent);
To this:
$($targetElement).html($newContent);
I think the problem is the div element with id="booksList" is replaced after first search. So you don't have this element in the second search.
I looked through the code step by step and found a solution to my problem.
In the first search, replace id="booksList"
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
partial view in which there was only without id = booksLists.
In the next search there was no ID in this place and there was nothing to replace.

After clicked on Link Count One Down (-1) from Total of Count JavaScript - MVC

I have page ,where im showing all messages and in header im showing Total of messages by counting them and im looking for something with javascript or MVC ,when user click on link (its means message be opened) count one down (-1) of total count which is messages and then use localstorage or Cookies to remember the count for next time, when user coming back to check their messages.
Can anyone please help me or point me in the right direction!
Thanks in advance :)
For example : lets say i have 14 messages , when user click on link i should be 13
Controller:
public ActionResult Messages(RMAHistory m2)
{
string EmailID = Session["Email"].ToString();
ViewBag.CountMSG = (new DbNamespace().Besked.Where(x => x.KundensEmail == EmailID).Select(f => f.KundensEmail).ToList().Count);
var bla7 = (from RB in db.Besked
where RB.KundensEmail == EmailID
select new RMAHistory.Comment_List
{
id = RB.ID,
MSG = RB.MSG,
se = RB.Seen,
Date = RB.Date,
Forfatter = RB.Writer,
KundensEmail =RB.KundensEmail,
Id = RB.RMAID,
MSGType =RB.MSGType
});
m2.Comment_Lists = bla7.ToList();
return View(m2);
}
View:
<div class="col-lg-8 col-md-7 col-md-offset-2">
<div class="card">
<div class="card-header" data-background-color="purple">
<span class="category">(You have #ViewBag.CountMSG New Messages)</span>
</div>
<div class="content">
#if (!Model.Comment_Lists.Any())
{
<div class="bs-callout bs-callout-danger">
<h4>You Do not Have New Messages</h4>
</div>
}
else
{
foreach (var item in Model.Comment_Lists)
{
if (item.se == "Kunde")
{
<div class="bs-callout bs-callout-success message">
<div class="col-xs-3 text-right">
<a target="_blank" href="/Account/RMADetails?id=#item.Id" id="#item.id" class="btn btn-sm btn-success btn-icon btnChangestu"><i class="fa fa-envelope"></i></a>
</div>
<h4><i class="fa fa-bookmark-o" aria-hidden="true"></i> Message number #item.Id</span></h4>
<span class="text-muted"><small> #item.Date.ToString("dd/MMMM/yyy")</small></span><br />
<span class="text-muted status"><span> #item.MSGType</span></span>
<input type="hidden" name="ChangeStu" id="ChangeStu" value="read massage" />
</div>
}
}
}
</div>
</div>
</div>
JavaScript:
<script>
$(document).ready(function () {
$('.btnChangestu').click(function () {
var id = $(this).attr('id');
if (!id) {
return;
}
var button = $(this);
var status = $(this).closest('.message').find('.status');
$.ajax({
type: "POST",
url: '#Url.Action("UpdateMSGStatus", "Account")',
data: {
IDMSG: id,
ChangeStu: $("#ChangeStu").val()
},
dataType: 'json',
success: function (result) {
if (result) {
status.text("read message");
button.removeData('id')
console.log("Ok")
} else {
// display error?
console.log("error");
}
},
error: function () {
console.log('something went wrong - debug it!');
}
})
});
});
</script>

change an element's text with variable id

I am designing a social network that has timeline and there is like button. I use AJAX to apply the like button on the server side. the problem is that I want to change the number of like for each post immediately after they have liked successfully. Because my elements are generated by for-each, I want to change the number of like for the exact element, I really have a problem with it.I am using thymeleaf.
I am looking for an idea that how to do this.
here is my html code:
<div class="col-sm-4">
<div class="row" >
<div class="col-sm-12">
<img th:if="${tweet.isFavorited()}" src="../static/images/like.png" th:src="#{/images/like.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/>
<img th:if="${!tweet.isFavorited()}" src="../static/images/dislike.png" th:src="#{/images/dislike.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/>
</div>
</div>
<div class="row">
<div class="col-sm-12" >
<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6>
<h6 th:if="${!tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getFavoriteCount()}"></h6>
</div>
</div>
and it is my script code:
$(function () {
$(".like-img").click(function () {
event.preventDefault();
var $post = $(this);
var toSend = {
"tweetId": this.getAttribute("id")
}
$.ajax({
type : "POST",
contentType: "application/json; charset=utf-8",
url : "like",
data : JSON.stringify(toSend),
dataType : 'json'
}).done(function (data) {
if(data.status == "success") {
if ($($post).attr("src") == "/images/dislike.png") {
$($post).attr('src','/images/like.png');
}
else {
$($post).attr('src','/images/dislike.png');
}
return false;
}
});
});
})
Okay so to make this work you will need to assign unique ids to the like-count elements, something like so:
<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}_like_count" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6>
Then you can retrieve the current count, increment it, and set the text of the count element. Something like so:
var currentCount = parseInt($('#'+toSend.tweetId+'_like_count').innerHtml)
var newCount = currentCount++;
$('#'+toSend.tweetId+'_like_count').text(newCount);

Jquery click function trigger load more button

below i have 3 links as an tabs:
<li data-tab-id="self" class="tab selected">Near You<span class="unread-count hidden" style="display: none;"></span></li>
<li data-tab-id="friends" class="tab">Following<span class="unread-count hidden" style="display: none;"></span></li>
<li data-tab-id="user" class="tab">Your Activity<span class="unread-count hidden" style="display: none;"></span></li>
when i click the above link Jquery click function are triggered
$(".hd-ui-activity li a").click(function(e) {
e.preventDefault();
var tabid = $(this).parent().attr('data-tab-id');
if(tabid == "self"){
getFunc1(totalRecords);
} else if(tabid == "friends") {
getFunc2(totalFriendsRecords);
} else if(tabid == "user") {
getFunc3(totalUserRecords);
}
});
When each of the links/tabs are clicked the function eg getFunc1() are called which append an html to the following div (Each func have its own div)
<li data-section-id="following" data-component-bound="true">
<ul class="module-list">
<!-- USER ACTIVITY JSON -->
</ul>
<a class="ybtn ybtn-primary ybtn-large more-wishlist" href="#" onclick="javascript:getRecentActivityFriends(event)">
<span data-component-bound="true" class="loading-msg following">See more recent activity</span>
</a>
</li>
Only 4 list results are displayed on the div, when user click see more activity button, more result are loaded into div. The problems now is when the page load it display correctly 4 results but when i click the link again rather than a button all the data are displayed.Its difficult for me to navigate between tabs. How can i avoid this?
Update:
var totalFriendsRecords = '<?=$this->followingTotal?>';
function getRecentActivityFriends(event)
{
if (event != null){
disabledEventPreventDefault(event);
}
getFriendsActivity(totalFriendsRecords);
}
home.js
var totalFriendsRecordsView = 0;
function getFriendsActivity(totalFriendsRecords)
{
var activityHtml = ''
$.ajax({
url:baseUrl + "activity/feedfollowing",
data:{'total':totalFriendsRecordsView},
dataType:"json",
type:"POST",
success:function(data){
for(var i=0; i<data.length; i++){
activityHtml = '<p>'+data[i][name]+'</p>';
}
$('#activity-feed li[data-section-id=following] .module-list').append(activityHtml);
if( totalFriendsRecords <= totalFriendsRecordsView){
$('.following').text('Nothing beyond here ...');
$('.following').removeAttr('onclick');
$('.following').removeAttr('href');
}
}
});
}

Categories