How to change fontawsome class name with ajax? - javascript

I want to change the icon after deleting row. Should I only use font awesome icon once in blade, then remove the class name, then add the class name with ajax?
blade:
<div id="status-{{ $country->id }}">
<div id="icon-{{$country->id}}">
#if( getStatus($country->status) == 'Active' || getStatus($country->status) == 'Aktif' )
<i class="fa fa-check-circle text-success"></i>
#elseif( getStatus($country->status) == 'Inactive' || getStatus($country->status) == 'Pasif' )
<i class="fas fa-minus-circle text-info"></i>
#else
<i class="fas fa-times-circle text-danger"></i>
#endif
<strong>{{ getStatus($country->status) }}</strong>
</div>
</div>
ajax:
$.ajax({
url: url,
type: "DELETE",
header: {
_token: "{{ csrf_token() }}",
},
success() {
toastr['error']("{{ __('home.delete.message') }}");
swal("{{ __('home.delete.message') }}", {
icon: "success",
});
$('#status-' + id).text('Deleted')
$('#icon-' + id).attr('i').addClass('fas fa-times-circle text-danger')
},
error(error) {
toastr['warning']("{{ __('home.error.message') }}");
}
});

JQuery's .attr() function is used to change the element's attribute. It has nothing to do with it's children.
Replace
$('#icon-' + id).attr('i').addClass('fas fa-times-circle text-danger')
with this
$('#icon-' + id + ' i').eq(0).attr('class', 'fas fa-times-circle text-danger');

Related

Toggle fa fa button is not changing when clicked

I am building a BlogApp and I am trying to make a like button which changes when clicked. BUT when i click on star button then it doesn't fill with color.
Like is successfully adding BUT star like button is not changing.
template.html
{% for i in p.likes.all %}
{% if user == i.liker %}
<a class='likebutton' data-catid="{{ p.id }}"><i id='like{{ p.id }}' class="btn fa fa-star-o fa-lg post-buttons "></i></a>
{% elif forloop.last %}
<a class='likebutton' data-catid="{{ p.id }}"><i id='like{{ p.id }}' class="btn fa fa-star-o fa-lg post-buttons "></i></a>
{% endif %}
{% empty %}
<a class='likebutton' data-catid="{{ p.id }}"><i id='like{{ p.id }}' class="btn fa fa-star-o fa-lg post-buttons "></i></a>
{% endfor %}
main.js
$('main').on('click', '.likebutton', function(){
var catid;
catid = $(this).attr("data-catid");
$.ajax(
{
type:"GET",
url: "/likepost/",
data:{
post_id: catid
},
success: function(data){
if(data==0){
$('.like' + catid).toggle();
$('#like' + catid).find('#like').toggleClass('fa-star-o fa-star');
$('#likecount' + catid).html('');
console.log(data+'if');
}
else if(data==1){
if($('.like' + catid).is(":hidden"))
{
$('.like' + catid).toggle();
}
$('#like' + catid).find('.like').toggleClass('fa-star-o fa-star');
$('#likecount' + catid).html(data + ' like');
console.log(data+'elseif');
}
else{
$('#like' + catid).toggleClass("far fas");
$('#likecount' + catid).html(data + ' likes');
console.log(data+'else');
}
}
})
});
main.css
:root {
font: 400 16px/1.5 Verdana;
}
.like {
display: inline-block;
font: inherit;
padding: 0px 5px;
cursor: pointer;
}
.like::after {
content: ' Favorite'
}
Any help would be much Appreicated. Thank You in Advance.
I think it's because #like element doesn't exist:
$('#like' + catid).find('#like').toggleClass('fa-star-o fa-star');
Maybe try:
$('#like' + catid).toggleClass('fa-star-o fa-star');

Need to hide whole table row when click on delete button in jQuery [duplicate]

This question already has answers here:
$(this) inside of AJAX success not working
(2 answers)
Closed 2 years ago.
I'm working on an application by using jquery ajax mathod and trying to delete table row by clicking on delete button. The backend part of php is fine but what i'm trying to apply is hide or fadeOut() jquery method on click event but unable to get the result. See following code:
$('.deletePageBtn').on('click', function(e) {
e.preventDefault();
if (confirm('Do you really want to delete this page?')) {
var pageId = $(this).data("pageid");
$.ajax({
url: "<?= base_url('admin/pagemanagerSavePage')?>",
type: 'POST',
data: {
action: "delete-page",
pageId: pageId
},
success: function(data) {
if (data == 'success') {
$(this).parent().parent().remove();
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
};
});
<tr id="rowId_26" class="rowData odd" role="row">
<td class="text-center sorting_1">3</td>
<td class="bg-success text-light text-center">
<i class="fas fa-eye"></i>
</td>
<td>
Pawan Mall - Internet Geek 123
<div class="btn-group float-right">
<a href="#" class="btn btn-sm btn-primary" target="_blank">
<i class="fas fa-eye"></i> View Page
</a>
<a href="" id="editPage" class="btn btn-sm btn-warning">
<i class="fas fa-edit"></i> Edit Page
</a>
<a href="" data-pageid="26" class="btn btn-sm btn-danger deletePageBtn">
<i class="fas fa-trash"></i> Delete Page
</a>
</div>
</td>
</tr>
The issue here is inside ajax success:
success: function(data) {
if (data == 'success') {
$(this).parent().parent().remove();
}
console.log(data);
},
this refers to the jqXHR object of the Ajax call. Its not same $('.deletePageBtn') element anymore. To make this work you can cache this at start inside click event like:
var $this = $(this);
and then use it inside success like:
success: function(data) {
if (data == 'success') {
$this.parent().parent().remove();
}
console.log(data);
},
or, better:
success: function(data) {
if (data == 'success') {
$this.closest('tr').remove();
}
console.log(data);
},

Jquery favorite function call api with ajax

I'm trying to create a favorite function in my django template that let user click on the icon and it will call to an api i made to send add and remove that favorite item from user data.
Currently how it work is if user click on the icon(favorite or unfavorite) it will call to an api that handle add favorite or remove favorite, and also it will replace the DOM of that tag with the opposite (for example if i click on favorite then the entire tag of it will be replace with tag content that has unfavorite icon and onclick function)
here my html for the tag, it display base on if it is favorite or not( {% %} tag is django handling it ):
<div class="article-category">{{ property.get_type_display }}
<div class="bullet"></div> {{ property.publish_date|date:'d-m-Y' }}
{% if not request.user|is_favorite:property.id %}
<a id="mylink" href="javascript:onclickFunction()" value="{{ property.id }}">
<i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i>
</a>
{% else %}
<a id="mylink2" href="javascript:onclickFunction()" value="{{ property.id }}">
<i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite"></i>
</a>
{% endif %}
</div>
And here is my jquery script:
<script>
$(document).ready(function () {
$('#mylink').on('click', function (event) {
event.preventDefault();
property_id = $(this).attr("value")
$.ajax({
type: "POST",
url: "http://localhost:9999/api/add_favorite/" + property_id + "/",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
},
success: function (data) {
if (data.code == 200) {
alert('ok');
replace_part_1 = '<a id="mylink2" href="javascript:onclickFunction()" value="' + property_id +'"><i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite></i></a>'
$("#mylink").replaceWith(replace_part_1);
}
}
});
return false;
});
$('#mylink2').on('click', function (event) {
event.preventDefault();
property_id = $(this).attr("value")
$.ajax({
type: "DELETE",
url: "http://localhost:9999/api/remove_favorite/" + property_id + "/",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
},
success: function (data) {
if (data.code == 200) {
alert('ok');
replace_part_2 = '<a id="mylink" href="javascript:onclickFunction()" value="' + property_id +'"><i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i></a>'
$("#mylink2").replaceWith(replace_part_2);
}
}
});
return false;
});
});
</script>
Now the first time i click on favorite or unfavorite it sent to the api and work, the replace html part for "#mylink2" onclick event but the "#mylink" replace doesn't include the tag which contain the icon.
After this any clicking event after that won't work and i have to refresh the page to click it again to work. Any click event after that also return this error:
Uncaught ReferenceError: onclickFunction is not defined
at :1:1
I'm super noob at jquery so i can't seem to find what is wrong, hope someone can help me
EDIT:
i changed my script to this by replace with value attribute of anchor tag:
<script>
$(document).ready(function () {
$('.article-details').on('click', '#mylink', function(event) {
event.preventDefault();
property_id = $(this).attr("value")
$.ajax({
type: "POST",
url: "http://localhost:9999/api/add_favorite/" + property_id + "/",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
},
success: function (data) {
if (data.code == 200) {
alert('ok');
replace_part_1 = '<a id="mylink2" href="#" value="' + property_id +'"><i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite></i></a>'
$("a[value='" + property_id + "']").replaceWith(replace_part_1);
}
}
});
return false;
});
$('.article-details').on('click', '#mylink2', function(event) {
event.preventDefault();
property_id = $(this).attr("value")
$.ajax({
type: "DELETE",
url: "http://localhost:9999/api/remove_favorite/" + property_id + "/",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
},
success: function (data) {
if (data.code == 200) {
alert('ok');
replace_part_2 = '<a id="mylink" href="#" value="' + property_id +'"><i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i></a>'
$("a[value='" + property_id + "']").replaceWith(replace_part_2);
}
}
});
return false;
});
});
</script>
and my html to:
<div class="article-category">{{ property.get_type_display }}
<div class="bullet"></div> {{ property.publish_date|date:'d-m-Y' }}
{% if not request.user|is_favorite:property.id %}
<a id="mylink" href="#" value="{{ property.id }}">
<i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i>
</a>
{% else %}
<a id="mylink2" href="#" value="{{ property.id }}">
<i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite"></i>
</a>
{% endif %}
</div>
it worked but the onclick of #mylink when changing the html the i tag inside still disappear(the #mylink2 onclick worked it changed the html white the tag)
It looks like you are facing an event delegation problem. That is, the moment your jQuery code runs, $('#mylink2') does not exist in the document and hence the event doesnt get binded. Use event delegation instead:
$('.article-category').on('click', '#mylink2', function(event) {
event.preventDefault();
// your original click handler
});
#myParentWrapper should be an element that is consistent in your markup, preferably not body or document for performance reasons.
You can then remove the onclick attribute from your anchor - or - actually somewhere define the function that is referenced there if it should do anything other than what your jQuery code does already.

Ajax success function with data-id

I have a feed page that loads an individual feedLikes.php for each post on the feed. Currently, I can like each post and it updates the likes using Ajax. However, every time a like is updated, it returns to the top of the feed. Below is feedLikes.php:
if (isset($_POST['feedID'])) {
$feedID = ($_POST['feedID']);
$findHasUserLiked = $pdo->prepare('SELECT username FROM feedLikes WHERE feedID =? and username=?');
//execute query and variables
$findHasUserLiked->execute([$feedID, $username]);
if ($findHasUserLiked->rowCount() > 0) {
$hasUserLiked = $findHasUserLiked->fetchColumn();
echo <<<_END
<form action="feedLikes.php" id="unlikePostForm$feedID" method="post">
<button type="submit" class="unLikeButton"></button>
<input type="hidden" name="feedIDForUnlike" class="feedIDForUnlike$feedID" value="$feedID">
</form>
_END;
?>
<script type="text/javascript">
$(document).ready(function () {
$('#likePostForm<?php echo $feedID ?>').on('submit', function (e) {
e.preventDefault();
var feedIDLike = $(".feedIDForLike<?php echo $feedID ?>").val();
$.ajax({
url: "feedLikesClicked.php",
cache: false,
type: "POST",
data: {
feedIDLike: feedIDLike
},
dataType: "html",
success: function (html) {
location.reload();
}
});
});
});
</script>
<?php
} else {
echo <<<_END
<form action="feedLikes.php" id="likePostForm$feedID" method="post">
<button type="submit" class="likeButton"></button>
<input type="hidden" name="feedIDForLike" class="feedIDForLike$feedID" value="$feedID">
</form>
_END;
?>
<script type="text/javascript">
$(document).ready(function () {
$('#likePostForm<?php echo $feedID ?>').on('submit', function (e) {
e.preventDefault();
var feedIDLike = $(".feedIDForLike<?php echo $feedID ?>").val();
$.ajax({
url: "feedLikesClicked.php",
cache: false,
type: "POST",
data: {
feedIDLike: feedIDLike
},
dataType: "html",
success: function (html) {
location.reload();
}
});
});
});
</script>
<?php
}
$likesNumber = $pdo->prepare('SELECT count(*) FROM feedLikes WHERE feedID =?');
//execute query and variables
$likesNumber->execute([$feedID]);
$numberOfLikes = $likesNumber->fetchColumn();
print '<div class=numberOfLikes data-id="' . $feedID . '">
<p>' . $numberOfLikes . '</p>
</div>';
}
I'm aware this is because location.reload() is actually reloading all the feedLikes.php pages, not just the one post i have liked. However, i can't seem to figure out what success function i need to use to just update the one post and not take me back to the top of the feed.
I have tried placing everything in feedLikes.php in a div like so:
<div class=allLikesPage data-id="'.$feedID .'">
and then in the ajax success using this line:
$('.allLikesPage[data-id='"+ feedID +"']').load(document.URL + ' .allLikesPage[data-id='"+ feedID +"']');
However that just removes everything and doesn't update. I've also tried the same thing without the data-id amongst other things.
there you go you can see the example here I had to show how the ajax response should be encoded so I added the example on my domain
your PHP file will look like the following, I have omitted the SQL part and added only the logic on how to use json_encode with the arrays hope you find it helpful you can use this code on your local machine to look into how things are working
<?php
$response = array('success'=>false,'likes'=>0);
if(isset($_POST['count'])){
$counter = $_POST['count'];
$response['likes']=$counter+1;
$response['success']=true;
}
echo json_encode($response);
?>
your HTML page is below
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<style>
.feed {
width: 95%;
height: auto;
}
i.fa {
cursor: pointer;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$(".voteup").click(function () {
var curElement = $(this);
console.log(curElement.parent().find('.likes').text());
$.ajax({
url: 'test.php',
dataType: 'json',
data: 'count=' + curElement.parent().find(".likes").text(),
method: 'POST'
}).done(function (data) {
if (data.success) {
curElement.parent().find(".likes").html(data.likes);
} else {
alert('Some Error occoured at the server while liking the feed');
}
});
});
});
</script>
</head>
<body>
<div class="panel panel-default">
<div class="panel-heading">Panel Heading</div>
<div class="panel-body">
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>Another feed item</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
<div class="feed">
<p>This is my feed can someone like it</p>
<i class="fa fa-thumbs-up voteup" aria-hidden="true" ></i>
<span class="likes">0</span>
<i class="fa fa-thumbs-down votedown" aria-hidden="true" ></i>
<span class="dlikes">0</span>
</div>
</div>
</div>
</body>
</html>
EDIT:
Basically, I am just incrementing the posted variable count you do not have to do that you just need to update likes in the database once you send the ajax call and then count with an SQL query and show the output in the same format I have used.And about the $.parseJSON() you will notice that the ajax call used here has the dataType set to JSON if you have set the dataType you do not need to parse the response otherwise you should use var myData=$.parseJSON(data); and then use like myData.likes myData.success

How to put <a href on that like which is 3? I'm using javascript

How to put an anchor tag <a href on that number 3 using javascript? Below is my source code:
$('.vote').click(function(e) {
e.preventDefault();
var product_id = $(this).data('product_id');
var voteCount = $(this).siblings('.vote_count');
$(this).siblings('a.vote').removeClass('active');
$(this).toggleClass('active');
if( !$(this).hasClass('active')){
$.get("{{ URL::route('unvote') }}", {product_id: product_id}).done( function(data){
console.log(data);
voteCount.text(data[0].vote_count);
});
} else {
if( $(this).hasClass('upvote')){
$.get("{{ URL::route('upvote') }}", {product_id: product_id}).done(function(data){
voteCount.text(data[0].vote_count);
});
} else {
$.get("{{ URL::route('downvote') }}", {product_id: product_id}).done( function(data){
voteCount.text(data[0].vote_count);
});
}
}
});
Below is image for reference, here under the price tag I want to put anchor tag:
Here's my view code:
if(Auth::check()) {
echo ' <div class="pull-left" style="margin-left:80px" > <a class="vote upvote" data-product_id="'.$products[$product]->product_id.'" href="hehehe"> <span class="fa fa-thumbs-up"></span> </a> '; } echo '<span class="vote_count"></span>'; if(Auth::check()) { echo '<a class="vote downvote" data-product_id="'.$products[$product]->product_id.'" href="#"> <span class="fa fa-thumbs-down"></span> </a> </div>';
}
The number 3 in your view is probably being rendered inside the following element:
<span class="vote_count"></span>
So why won't you wrap an a element around it?
</span>
Or you can do it dinamically with jQuery using wrap():
$(".vote_count").wrap("<a href=''></a>");

Categories

Resources