Insert html element after count in Jquery - javascript

var num = parseInt($.trim($(this).text()));
$(this).html('<i class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"></i>', ++num);
After a certain div gets clicked the count must go up. This actually works but alongside with that an icon has to be added to the clicked div. How would I do this? The above sample work, but only the <i> gets inserted.
EDIT:
The dataset-postid="{{ $post->id }}" defines the post_id that has this like button. What has to be changed is {{ $likes}}
```
<div class="wis-numbers">
<?php $likes = $post->likes->count() ?>
<span id="like" class="like" data-toggle="tooltip" data-placement="bottom">
<i class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"></i>
{{ $likes }}
</span>
</div>
I tried to solve this with only updating text with Jquery, like this:
var num = parseInt($.trim($(this).text()));
$(this).text(++num);
But then this disappears from my html <i class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"> So I have to include it somehow with the count.
This is my full AJAX/Jquery for this button, basically if the button ges clicked, the count must go up (or down if disliked) and a class 'active' needs to be added
$('.like').on('click', function(event) {
event.preventDefault();
postId = event.target.dataset['postid'];
if($(this).hasClass('active')) {
$(this).removeClass("active");
$.ajax({
method: 'POST',
url: urlLike,
data: { postId: postId, _token: token },
});
console.log('unlike');
} else {
$(this).addClass("active");
$.ajax({
method: 'POST',
url: urlLike,
data: { postId: postId, _token: token },
});
console.log('like');
}

Related

How to keep favorite / unfavorite button color after page reload?

I'm working on a Laravel project where user can favorite and unfavorite books, when user clicks on favorite button , the color changes to red and when clicked again it's color back to gray , in the two cases the DB changes successfully without page reloading as i used ajax , but the problem now is that when i refresh the page, the button back to gray color.
here is the code of my view:
// i removed most html code
#foreach( $books as $book)
<div class="mb-3">
<span class="badge badge-pill badge-primary p-2 mr-4">
<span class="count_of_book">{{ $book-> amount }}</span>
copies available
</span>
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x"></i>
</div>
</div>
#endforeach
// ajax link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var token = '{{ Session::token()}}';
var urlFav = '{{ route('favor') }}';
</script>
and the code of js:
$(".fa-heart").on("click", function (event){
bookid = $(this).data("bookid");
$.ajax({
method: 'POST',
data: {bookid: bookid , _token:token},
success: function(data){
if(data.is_fav == 1){
$(event.target).toggleClass('heart-active');
}
if(data.is_fav == 0){
$(event.target).addClass('text-dark');
}
}
});
and the php code on controller:
public function bookFavBook(Request $request){
$book_id = $request['bookid'];
$fav = DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->first();
if(!$fav){
$newfav = new Favorite;
$newfav->book_id =$book_id;
$newfav->user_id = Auth::user()->id;
$newfav->fav = 1;
$newfav->save();
$is_fav = 1;
}
elseif ($fav->fav == 1){
DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->delete();
$is_fav = 0;
}
elseif ($fav->fav == 0){
DB::table('favorites')
->where('book_id', $book_id)
->where('user_id', Auth::user()->id)
->update(['fav'=> 1] );
$is_fav = 1;
}
$response = array(
'is_fav'=>$is_fav,
);
return response()->json($response, 200);
}
}
and finally the route used :
Route::post('/favor', [ 'uses'=>'BookController#bookFavBook','as'=>'favor']);
please any one can help, i just want to keep button color even after page reload and every time user log in.
thank you
You need to get the favorite books list and loop through the list to compare with the books. Below code gives you the idea,
#foreach( $books as $book)
#foreach($favBooks as $fav) // Pass Favorite books list from controller.
<div class="mb-3">
<span class="badge badge-pill badge-primary p-2 mr-4">
<span class="count_of_book">{{ $book-> amount }}</span>
copies available
</span>
<i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x {{ $fav->bookid == $book->id ? 'heart-active' : 'text-dark'}}"></i>
</div>
#endforeach
#endforeach

How to get the ID of a dynamically generated button using jQuery?

I need some help. I have a page where I display database records as a bootstrap button pill in a display div. I also have an Ajax Submit input that saves new records to the database and dynamically creates a button pill for the new record using the db record id for the button id. The jQuery below allows me to click on the new dynamically created button but it always displays ID = 1 and not the ID shown in view source.
Can someone please explain what I am doing wrong here?
Code of Button Pills created from PHP:
<div class="row">
<div class="col-md-8 col-sm-10 mx-auto mb-3">
<div class="decision-box">
<div class="decision-icon bg-orange-grad"><img src="../assets/img/logos/Sparck-Logo-Icon-Lg-White.png" alt="Sparck-Logo-Icon-Lg" width="40" height="40" /></div>
<div class="decision-text">
<form id="accolorform">
<input type="hidden" name="action" value="colorsave">
<input type="hidden" name="interesttype" value="Favorite Color">
<input type="hidden" name="userid" value="<?php echo $_SESSION['userid']; ?>">
Favorite Color:
<input type="text" class="form-control-inline col-auto no-border no-shadow" id="ac_color" name="interest" placeholder="Type something" autocomplete="off" style="min-width: 200px;">
<span class="float-right" style="margin-right: 15px;">
<button type="submit" class="btn btn-light" id="colorbtn">Add</button>
</span>
</form>
</div>
</div>
<div id="color_pills">
<?php if(!empty($resultlist) && isset($resultlist)){
foreach($resultlist as $r){
if($r['interesttype'] = "Favorite Color"){ ?>
<button id="btn<?php echo $r['id']; ?>" class="btnpill" title="Are you sure you want to delete <?php echo $r['interest']; ?>?"><?php echo $r['interest']; ?> <i id="<?php echo $r['id']; ?>" class="fal fa-minus-circle delete"></i></button>
<?php }
}
}?>
</div>
</div>
</div>
Code of jQuery aJax that creates dynamic button
$("#accolorform").validate({
rules: {
ac_color: {
required: true
}
},
messages: {
ac_color: {
required: 'Please select a Color'
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $(form).serialize(),
success: function(id){
//alert("Color Added");
var name = $("#ac_color").val();
var newpill = '<button id="btn'+id+'" class="btnpill" title="Are you sure you want to delete '+name+'?">'+name+' <i id="'+id+'" class="fal fa-minus-circle delete"></i></button>';
$("#color_pills").append(newpill);
$("#accolorform")[0].reset();
},
error: function(){
alert("Error");
}
});
}
});
Code of Ajax Delete where I am trying to grab dynamic button id:
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
var title = $('#btn'+id).attr('title');
var string = 'source=interests&id='+ id ;
if (confirm(title)) {
$.ajax({
type: "POST",
url: "ajaxdelete.php",
data: string,
cache: false,
success: function(){
$('#btn'+id).remove();
}
});
}
return false;
});
The above code looks like it should work and view source shows a button tag that is formatted like the ones created by PHP that work perfectly.
I appreciate any help!

Button Change Error on Click Javascript

2 buttons are supposed to be "Add to Favorites" and "Extract from Other Favorites". Here's my code:
<button type="submit" class="btn btn-warning btn-xs" id="FavoriButonex" data-id="<?php echo $sorid ?>">
<i class="fa fa-heart-o"></i> Fovorilerimden Çıkar
</button>
<button type="submit name="favekle" class="like btn btn-success btn-xs" id="FavoriButon" data-id="<?php echo $_GET['soru_id']; ?>" >
<i class="fa fa-heart-o"></i> Fovorilerime Ekle
</button>
JavaScript code:
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/behaviour/general.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#FavoriButon').click(function(){
var soru_id = $(this).attr('data-id');
$.ajax({
url: 'soru-detay.php',
type: 'post',
data: {
'favoriad': 1,
'soru_id': soru_id
},
success: function(){
}
});
});
$('#FavoriButonex').click(function(){
var soru_id = $(this).attr('data-id');
$.ajax({
url: 'soru-detay.php',
type: 'post',
data: {
'favoriex': 1,
'soru_id': soru_id
},
success: function(){
}
});
});
});
</script>
I'm working on but the button does not change.
When we press the insert button, the eject button should come
button id="FavoriButonex" Click to button id="FavoriButon"
This was translated to English via machine translation (before edits), I apologize for any errors.
Change the type for the button to button
type="button" you are currently submitting a form(if you have any),
note: you also don't do anything with the ajax response, you need to notify that the ajax was successful or not, alter your success functions

delete record from database without refreshing

I have an code where it is supposed to delete the data without refreshing. the delete process works but i have to refresh to to remove the data.
heres my code please help me
Ajax:
$(function () {
$(".trash").click(function () {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type: "POST",
url: "delete.php", //URL to the delete php script
data: info,
success: function () {}
});
$(this).parents(".record").animate("fast").animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
Here's my html:
<td style="padding-left: 23px">
<img class="photo" data-toggle="modal" data-target="#gallery<?php echo $photo; ?>" src="<?php echo $r1['photo']; ?>" />
<div class="hotel">
<button class="trash" id="<?php echo $r1['photo_id']; ?>" > <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
</div>
</td>
If I hover the button to the image the .trash button will appear and if I click it the image must be deleted. help me please.
You can give a data image id attr to parent tr,
<tr data-image-id="<?php echo $r1['photo_id']; ?>">
After successful delete process (in your ajax success function) you can run code below.
$("tr[data-image-id="+del_id+"]").remove();
Your code works, maybe do you need show the complete html, or at least the classes ".record" to analyze the "error"
No need to add extra attribute for ID in table row(TR).
$('.glyphicon-remove').on('click',function() {
$(this).closest( 'tr').remove();
return false;
});
Try This:
function delete_value(id)
{
if(confirm('Are you sure you want to delete this?'))
{
// ajax delete data from database
$.ajax({
url : "<?php echo site_url('yoururl/del')?>/"+id,
type: "POST",
success: function(data)
{
$("tr[id="+id+"]").remove();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
<button class="btn btn-danger" onclick="delete_value(<?php echo $row->id;?>)"><i class="glyphicon glyphicon-remove"></i></button>
<!--- add tr id --->
<tr id="<?php echo $row->id; ?>">

On Span Click - Insert rows into MySQL with page refresh

I've got a page where I display rows from MySQL table.
while($row2 = $result2->fetch_assoc()) { ?>
<p>
<span class="label label-primary">
<?php echo ($row2["miasto"]); ?>
</span>
<span class="label label-primary delete" id="<?php echo ($row2["miasto"]); ?>"><i class="fa fa-times"></i></span>
</p>
on a span click .delete I would like to get this row deleted from a database and page refreshed without those rows and with alert to be present.
I'm able to do a on click action in Jquery:
$(document).ready(
function(){
$(".delete").click(function () {
$.post( "miastousun.php", { mdu: (this.id)} );
and than on php of miastousun.php:
$sql = "DELETE FROM miasta_zmiany WHERE Miasto_dodaj='".($_POST['mdu'])."";
but does not seem to work. What I'm doing wrong?
Try this ajax code.
$( document ).on( 'click', '.delete', function() {
var thisId = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'miastousun.php?mdu='+thisId,
success: function(data){
alert('Message something');
},
error: function(errorThrown){
alert(errorThrown);
}
});
});

Categories