Remove message from view? - javascript

Each time a user clicks un read the div area should remove, below is my HTML and javascript. Whats happening at the moment is that when you click unread it does everything in the back end and not in the front end screen, I think its got to do with my JavaScript line $('#Unreadmessage').closest(".messagearea").remove(); please advise
<div class="alert alert-default alert-dismissible messagearea" role="alert" style="background: rgb(233, 233, 233);">
<button class="close" aria-label="Close" type="button" data-dismiss="alert"><span aria-hidden="true">×</span></button>
<div id="Unreadmessage" class="markmessage" data-messageid="#message.Id">
<p class="small"><i class="fa fa-envelope" aria-hidden="true"></i> Unread</p></div>
<p class="small"><i class="fa fa-calendar" aria-hidden="true"></i> #message.CreatedOn.ToString("dd MMM yyyy")</p>
<p class="small" style="font-weight: bold;"><i class="fa fa-info" aria-hidden="true"></i> Claim ref. #message.CaseNumber</p>
<p>#message.Message More.</p>
</div>
Below is my Javascript
$("#Unreadmessage").click(function () {
var messageId = $(this).data("messageid"); //need to pass this message ID to controller.
var isread = true; //True by default
//I need to pass the messageID to server which is CRM
$.ajax({
url: "#Url.Action("MarkMessage", "Enquiry")", //Need to add my URl here
type: "POST",
data: { messageId: messageId, isread: true }, //Get messageId and isread values
dataType: "json",
success: function (response) {
$('#Unreadmessage').closest(".messagearea").remove();
}
});

If you mean removing the content just like clicking x, then that can also be achieved by just placing data-dismiss="alert" at p(the unread container).
To remove just the unread, it will be best to update the back-end to isread(for example) when More is clicked. You then have to decide whether to display Read or displaying nothing.
<p data-dismiss="alert" class="small"><i class="fa fa-envelope" aria-hidden="true"></i> Unread</p>

Related

How do i make div refreshing to work properly

FIXED
I have options for user to select if he is Online, Away...etc
When i select Away for example, in mysql database i get away status. So, selecting status is working perfect. The problem is that i want when user select status, function submit_status gets called and $('#statusRefresh').load(' #statusRefresh'); should refresh the div where his current status is displayed, but when i select for example Away, the status stays Online, and when i select Busy, the status changes to Away, but when i refresh the page, status goes to Busy. It's like late by one step, showing me only previous status. Sometimes happens like when i select, nothing happens, remains the old status, and when i select another, i get previous. The problem should be something about refreshing that div in correct time (when i select status).
This is the list of all statuses:
public function getStatusText($value){
if($value == '1'){
echo '<i class="fas fa-check-circle text-success"></i> Online';
}else if($value == '2'){
echo '<i class="fas fa-clock text-warning"></i> Away';
}else if($value == '3'){
echo '<i class="fas fa-minus-circle text-danger"></i> Busy';
}else if($value == '4'){
echo '<i class="fas fa-times-circle text-info"></i> Invisible';
}
}
This needs to be refreshed when i change status:
<li class="list-group-item" data-bs-toggle="modal" data-bs-target="#statusModal"><div id="statusRefresh"><?php echo $user->getStatusText(escape($user->data()->status)); ?></div>
This is how i select status:
<div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-darkblue">
<h5 class="modal-title" id="statusModalLabel">Status</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="d-grid gap-2">
<button type="button" onclick="submit_status(1)" class="btn btn-light border text-start"><i class="fas fa-check-circle text-success"></i> Online</button>
<button type="button" onclick="submit_status(2)" class="btn btn-light border text-start"><i class="fas fa-clock text-warning"></i> Away</button>
<button type="button" onclick="submit_status(3)" class="btn btn-light border text-start"><i class="fas fa-minus-circle text-danger"></i> Busy</button>
<button type="button" onclick="submit_status(4)" class="btn btn-light border text-start"><i class="fas fa-times-circle text-info"></i> Invisible</button>
</div>
</div>
</div>
</div>
</div>
This is how i call for refresh:
function submit_status(value){
$.ajax({
type: "POST",
url: "index.php",
data: {
value : value,
success: function (data) {
$('#output').html(data);
$('#statusModal').modal('hide');
$('#statusRefresh').load(' #statusRefresh');
}
}
});
}
FIXED:
function submit_status(value){
$.ajax({
type: "POST",
url: "index.php",
data: { value: value },
dataType: "html",
success: function (data) {
$('#output').html(data);
$('#statusModal').modal('hide');
$('#statusRefresh').load(' #statusRefresh');
}
});
}
I didn't notice that i put success inside data...

Accessing dynamically created variable in onclick

I have a foreach loop, enumerating my models to create a table. In this table, i need to have an edit button for each model where i call a javascript function to show a modal.
I need to pass the model into the javascript function, but i can't get this to work. I've worked out how to dynamically create the variables, but not how to use it as input.
Right now, it's just hardcoded to use 'department1', which is just the first created. I need toggleManageDepartmentModal to be called with (department + #department.Id)
Creating the table
#foreach (var department in Model.PaginatedDepartments())
{
<tr>
<td>#department.Name</td>
<td>#department.Description</td>
<td class="min">#department.Created.ToLocalTime().ToString("dd-MM-yyyy")</td>
<td class="min">
<div class="text-nowrap">
<script>
//Dynamically create variables for each department
eval('var department' + #department.Id + '= #Json.Serialize(department);');
</script>
<button type="button" class="btn btn-secondary btn-sm" onclick="toggleManageDepartmentModal(department1)">
<span class="fa-solid fa-pen-to-square" aria-hidden="true"></span>
Rediger
</button>
</div>
</td>
</tr>
}
Javascript function to show modal
function toggleManageDepartmentModal(department) {
var model = {
department : department,
controller : 'Admin',
action : 'ManageDepartment'
};
$.ajax({
type: "Post",
url: "/Modals/ShowManageDepartmentModal",
data:model,
success: function (data) {
$("#loadModal").html(data);
$('#modal-manage-department').modal('show')
}
})
}
I would like to do something like this:
<button type="button" class="btn btn-secondary btn-sm" onclick='toggleManageDepartmentModal(Eval("department" + #department.Id))'>
<span class="fa-solid fa-pen-to-square" aria-hidden="true"></span>
Rediger
</button>
I am not exactly familiar with the tool (a templating engine?) you are using to build your HTML, but I will try to help.
Traditionally, before the JS framework takeover, the way to attach data to HTML elements was to use data-attributes. In your case, I would use something like data-department. I would dare to say that it's much better way then using script tags + eval()
The simplest way would be to attach the data to the button. Probably like a serialized JSON:
<button data-department="#DataGoesHere" type="button" class="btn btn-secondary btn-sm">
Rediger</button>
How about the onclick function? You can get the button's reference by using this argument:
<button onclick="toggleManageDepartmentModal(this)" data-department="#DataGoesHere" type="button" class="btn btn-secondary btn-sm">
Rediger</button>
Then, you can access the data by querying this.dataset.department:
function toggleManageDepartmentModal(targetElement) {
// `this` is event's target element
const department = targetElement.dataset.department;
// or rather JSON.parse(targetElement.dataset.department)
// or targetElm.getAttribute('data-department')
…
}
There's one caveat – because data-attributes are part of the 'public' markup, you really should not put anything confidential in there (but I guess that this is not the case).
I ended up taking a little different approch which works very well.
#foreach (var department in Model.PaginatedDepartments())
{
<tr>
<td>#department.Name</td>
<td>#department.Description</td>
<td class="min">#department.Created.ToLocalTime().ToString("dd-MM-yyyy")</td>
<td class="min">
<div class="text-nowrap">
<script>
//Store model JSON in localStorage
localStorage.setItem('department' + #department.Id, JSON.stringify(#Json.Serialize(department)))
</script>
<button type="button" class="btn btn-secondary btn-sm" onclick="toggleManageDepartmentModal(#department.Id)">
<span class="fa-solid fa-pen-to-square" aria-hidden="true"></span>
Rediger
</button>
</div>
</td>
</tr>
}
function toggleManageDepartmentModal(id) {
var modelJSON = localStorage.getItem('department' + id);
var model = {
department : JSON.parse(modelJSON),
controller : 'Admin',
action : 'ManageDepartment'
};
$.ajax({
type: "Post",
url: "/Modals/ShowManageDepartmentModal",
data:model,
success: function (data) {
$("#loadModal").html(data);
$('#modal-manage-department').modal('show')
}
})
}

Flask add modal to ask before deleting. How to get working?

In my Flask APP i have a page with a link to delete:
Is inside a table each row have this id, here I am sending the ID (that normaly I use to delete):
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" id="submits" onclick="send_to_modal('{{post.id}}')">
Borrar
</button>
Here is my javascript:
function send_to_modal(id){
document.getElementById("exampleModalLabel").innerHTML = id;
};
The modal:
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" onclick="modal_a_funccion()">SI</button>
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">NO</button>
</div>
</div>
</div>
</div>
I don´t know how to send the ID to another function that is charged to delete the specified data:
This is my function that works correcty and delete the data giving the ID:
function modal_a_funccion(id){
console.log("Solicitando un report para: "+id);
//fetch('/report/' + olt_hostname).then(function(response) {
fetch('/task/report_celery/' + id).then(function(response) {
response.json().then(function(data) {
for (var x of data.ip) {
console.log("REPORT_fetch recibe (IP): " +x.ip_oob)
console.log("REPORT_fetch recibe (ESTADO): " +x.estado)
};
});
});
};
I would like to know how to to it.
What I intend to do is add a modal to ask the user for confirmation whether or not to delete. I can't find a way to pass the Id to the function that is in charge of doing the deletion. I would like to know how to do it. Thank you so much.
A possible solution (in a different way)
When user clicks on delete for a row, add a class e.g. to_delete. Then display the modal popup asking if user wants to go ahead with the delete or not.
If user says no, close the modal and remove the class again
If user says yes, call the delete function
For 3, you do something like
// Find the element that user has marked for delete
const element = document.querySelect(".to_delete")
const id = element.id;
For 2, you do something like
// Find the element that user has marked for delete and remove the delete mark
document.querySelect(".to_delete").classList.remove("to_delete")

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

Code is getting executed even when hitting cancel button (ajax)

Okay so I have a function "deactivate" which passes in 3 parameters to it.
<a href="#myModal" onclick="deactivate('{{ $user->getRoleName() }}', '{{ $user->getFullName() }}', {{ $user->id }}); return false;" role="button" data-toggle="modal" class="btn btn-danger btn-small delete">
<i class="btn-icon-only"></i>
Deactivate User
</a>
Here is my function:
function deactivate(title, name, id) {
$('#modal-user-role').html(title);
$('#modal-user').html(name);
$('#confirm').click(function() {
$.ajax({
url: '/user/' + id + '/',
type: 'PUT',
success: function (data) {
$('#alerts').html('<p class="alert alert-success">Successfully deactivated ' + title + ': ' + name + '</p>' + $('#alerts').html());
$('#r' + id).hide();
},
error: function (jqXHR, textStatus, errorThrown) {
$('#alerts').html('<p class="alert alert-error">A problem occured while deactivating ' + title + ': ' + name + '</p>' + $('#alerts').html());
$('#r' + id).hide();
}
});
});
}
Here is my HTML that goes with the function:
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close icon-remove" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel">Deactivate User</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to deactivate user <span id="modal-user-role"></span>: <span id="modal-user"></span>?</p>
<p>This action cannot be undone.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button id="confirm" data-dismiss="modal" class="btn btn-danger">Confirm Deactivation</button>
</div>
</div>
Does anyone know why my cancel button is not working? I believe it has something to do with the onclick I am using but not quite sure how to fix it.
So, basically if I click the deactivate user button and than cancel and click another user and then cancel and then click another user and than confirm the deactivation it will delete each user from the DB.
Which I do not want.
I have the button type="button" which I thought would fix it. But it is not.
Any ideas at all would be greatly appreciated.
As I mentioned in the comments, the problem is how you are registering the click handler...
since the click handler is registered within the deactivate method, every time the method is called a new handler is added - it doesn't remove the previously added handlers...
so you can try to remove the handlers using .off()
$('#confirm').off('click.deactivate').on('click.deactivate', function () {
})
Note: When using event unbinding I prefer using name spacing

Categories

Resources