I'm currently editing a back-end page, but I have a few problems.
I need a confirmation before I delete the Action as you can see I tried this so far but my code is completely skipping the confirm() and only redirects to the index.
Please take a look at the controller code below
delete(req, res, next) {
Action
.findOne(req.param('id'))
.then(({id}) => {
confirm('U staat op het punt een actie te verwijderen, klik op "ok" om hier mee door te gaan');
if(confirm()=== true) {
Action
.destroy(id)
.then(() => {
FlashService.setFlash(req, 'success', 'Action has been deleted')
res.redirect('/answer/index')
})
.catch(err => res.redirect('/answer/index'))
}
})
.catch(err => res.redirect('/answer/index'))
}
}
I also tried console.log to see where my code is stranding but that would only give this error:
Unhandled rejection ReferenceError: confirm is not defined
edit
I tought it also might be usefull to maybe see the HTML so here you go
as you can see the delete is called upon submit maybe I'm doing that extremly wrong but it seems to work besides the confirm mentioned before
<form action="/action/delete/<%= action.id %>" method="POST">
<button type="submit"
class="btn btn-sm btn-icon btn-pure btn-default on-default"
data-toggle="tooltip"
data-original-title="Verwijder"><i class="icon wb-trash" aria-hidden="true"></i>
</button>
</form>
EDIT 2.0
I kind of fixed the problem but still not really I made the following javascript for the delete it's a little basic but that isn't the problem please take a look
<script>
function Delete(){
let c = confirm('U staat op het punt een actie te verwijderen, klik op "ok" om hier mee door te gaan');
if (c){
console.log("done");
window.location.href = "/action/delete/<%= action.id %>"
}
else{
console.log("failed")
window.location.href = "/answer/show/<%= answer.id %>"
}
}
</script>
however, when I go to this page it says "action not defined" but I'm quite sure it is defined to be honest.
I don't really know what I'm doing wrong, any help would be nice
You cannot use the client side confirm javascript on the server side. It does not exist. You should instead call confirm before sending request to the server.
Like so
<button onclick="delete()">Delete</button>
<script>
function delete() {
var confirm = confirm("Do you want to delete?")
if(confirm){
// Call server
}
}
</script>
Related
I'm adding localstorage items on the websites of the companies I work for, and I've come across a problem on some websites; when adding the item to storage, it is displayed normally on the site, but when accepting and refreshing the page the message continues to appear, what could be causing this?
I checked that maybe it could be the version of JQuery I'm using (JQuery 1.7), but I updated the library and the error persists, can anyone help me?
JS Code:
function cookies(functions) {
const container = document.querySelector('.cookies-container');
const save = document.querySelector('.cookies-save');
if (!container || !save) return null;
const localPref = JSON.parse(window.localStorage.getItem('cookies-pref'));
if (localPref) activateFunctions(localPref);
function getFormPref() {
return [...document.querySelectorAll('[data-function]')]
.filter((el) => el.checked)
.map((el) => el.getAttribute('data-function'));
}
function activateFunctions(pref) {
pref.forEach((f) => functions[f]());
container.style.display = 'none';
window.localStorage.setItem('cookies-pref', JSON.stringify(pref));
}
function handleSave() {
const pref = getFormPref();
activateFunctions(pref);
}
save.addEventListener('click', handleSave);
}
function marketing() {
console.log('Função de marketing');
}
function analytics() {
console.log('Função de analytics');
}
cookies({
marketing,
analytics,
});
function fechar() {
document.getElementById('cookie').style.display = 'none';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
PHP Code:
<div class="cookies-container" id="cookie">
<div class="cookies-content">
<div>
<p>
Este site ultiliza cookies e outras tecnologias semelhantes para
melhorar a sua experiência em nossa plataforma. Você aceita
a politica de privacidade?
</div>
<div class="cookies-pref">
<button class="cookies-save btn btn-warning">Sim</button>
<button onclick="fechar()" class="btn btn-light cookies-no" style="color: #000;">Não</button>
</div>
<div class="politica">
Ver nossa política de privacidade?
</div>
</div>
</div>
<!-- <?= $CAMINHO ?>/index.php?sessao=<?= verifica($sequencia . $politicaPrivacidade . $complemento); ?>&id=<?= $menuNossaCidade['id'] ?> -->
(I'm using jquery 1.7)
hello so i write this code
module.exports.run = async (Client, message, args, prefix) => {
if (!message.content.startsWith(prefix)) return;
disbut(Client);
let button1 = new disbut.MessageButton()
.setStyle("green") //default: blurple
.setLabel("créer un channel") //default: NO_LABEL_PROVIDED
.setID("create"); //note: if you use the style "url" you must provide url using .setURL('https://example.com')
let button2 = new disbut.MessageButton()
.setStyle("red") //default: blurple
.setLabel("fermer un channel") //default: NO_LABEL_PROVIDED
.setID("close"); //note: if you use the style "url" you must provide url using .setURL('https://example.com')
message.channel.send("Cliquer sur les boutons pour effectuer une action ", {buttons : [button1, button2] });
};
if i execute my command the texte is send in my channel but not the button
and i dont understand why and i dont have any error
thanks for your help :)
In Discord.js v13, the send method only takes a single parameter. Discord.js is only looking at "Cliquer sur les boutons..." and not the second object you are providing.
Instead, use a single MessageOptions object:
message.channel.send({
content: "Cliquer sur les boutons pour effectuer une action ",
buttons: [button1, button2]
});
For more information, see this section in the Discord.js guide.
I am trying to change an Alert to a Modal, I have a function in Typescript to subscribe an user for example when the subscriber is ok, I can call a Modal of success, but I have another alert in this function if the subscribe not works, my question is, how can I change the second alert (which does not work the subscribe) from my function to a Modal of error? I mean, I want to put two different Modals for the same function.
I've tried to make a function in JavaScript, using Sweetalert2 and using with Angular, but both it didn't work, also something like this:
<swal #ok
type="success"
title="Cadastro realizado comsucesso!" (confirm)="CadastrarUsuario()">
</swal>
<swal #ok
type="error"
title="Cadastro não realizado!" (confirm)="CadastrarUsuario()">
</swal>
<button type="submit" [swal]="ok" class="btn btn-primary def-button">Cadastrar Usuário</button>
This is my function:
cadastro-user.component.ts
CadastrarUsuario() {
if (this.roleVisivel == 1) {
this.lider.perfil = "LiderTecnico";
this.funcionarioService.cadastrarFuncionarioPorAdmin(this.lider).subscribe (
data => {
// alert("CADASTRADO COM SUCESSO !")
location.reload();
},
error => {
alert("Algo de errado nao esta certo.")
}
);
} else if (this.roleVisivel == 2) {
this.user.admin = true;
this.usuariosService.cadastrarGerente(this.user).subscribe (
data => {
// alert("CADASTRADO COM SUCESSO !")
location.reload();
},
error => {
alert("Algo de errado nao esta certo.")
}
);
}
}
cadastro-user.component.html
<swal #ok
type="success"
title="Cadastro realizado comsucesso!" (confirm)="CadastrarUsuario()">
</swal>
<button type="submit" [swal]="ok" class="btn btn-primary def-button">Cadastrar Usuário</button>
I have a question regarding the use of sweet alert on Asp.net core 2.2 mvc. While trying to make an alert to confirm a post event on my controller AdminUsersController, the action returns an error because the requested id is null, but when I don't use sweet alert the event works perfect.
I'm trying to get this to work on Asp.net core 2.2 on Visual studio 2017 community, I've never had any problems before with crud operations regarding Id's. I'm trying to make it work on a table with many results with diffrent Ids.
like so : https://gyazo.com/9366bab83fa4401e1b88b28e27ffa55f
Controller Index Post
//== Action - Index
[Authorize(Roles = SD.Tier3User)]
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> Index(string id)
{
var UserFromDb = await _db.ApplicationUser.FindAsync(id);
if (UserFromDb.LockoutEnabled == true)
{
//== Lo desactiva (LockOutEnabled = 0)
UserFromDb.LockoutEnabled = false;
}
else
{
//== Lo activa (LockOutEnabled = 1)
UserFromDb.LockoutEnabled = true;
}
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
HTML button
<td>
#if (User.IsInRole(SD.Tier3User))
{
<a asp-action="Edit" asp-route-id="#item.User.Id" class="btn btn-sm
btn-outline-primary">Editar</a>
== HERE I USE SWEET ALERT ===
#if (item.User.LockoutEnabled)
{
<button type="submit" onclick="CambiarEstado()" asp-route-id="#item.User.Id" class="btn btn-sm btn-outline-warning">Desactivar</button>
}
else
{
<button type="submit" onclick="CambiarEstado()" asp-route-id="#item.User.Id" class="btn btn-sm btn-outline-success">Re-activar</button>
}<a asp-action="Delete" asp-route-id="#item.User.Id" class="btn btn-sm btn-outline-danger"><i class="far fa-trash-alt"></i></a>
}
</td>
JS Sweet alert
<script>
function CambiarEstado() {
document.querySelector('#Estado').addEventListener('submit', function (event) {
var form = this;
event.preventDefault();
swal({
title: "¿Desea cambiar el estado de este usuario?",
icon: "success",
buttons: [
'No',
'Si'
],
}).then(function (isConfirm) {
if (isConfirm) {
swal("¡Estado cambiado!", {
buttons: false,
timer: 500,
}).then(function () {
form.submit();
});
} else {
swal("Acción cancelada", "Recuerde que un usuario desactivado no puede entrar al sistema", "error");
}
})
});
}
</script>
It was suppose to de-activate the user, but first ask if I'm sure of that action, Instead it returns an error since the id the post event got was null.
Thanks in advance!
The asp-route-* attribute is not valid on a button element. That attribute is specifically utilized by the AnchorTagHelper (i.e. for a elements). You need to either use an actual anchor tag, and simply style it as a button:
<a onclick="CambiarEstado()" asp-action="Foo" asp-route-id="#item.User.Id" class="btn btn-sm btn-outline-warning">Desactivar</a>
Or you'll need to create a hidden input within your form tag to hold the id:
<input type="hidden" name="id" value="#item.User.Id" />
Note: it's unclear what's actually happening here, so you should bear in mind that if you use the action link approach, that will not submit anything. It's a regular GET request at that point, and the id will be added as query param to the href that's generated (hence the need to also specify asp-action). More likely than not, you want to stick with the button and add a hidden input.
Goal: I'm trying to create a button that allows users to like posts on a website, (similar to the way Facebook does it), which would also increment/decrement the number of likes besides the button as well.
Issue: Everything works well except in one edge case. If the user has already liked the post, he can unlike it but no longer like it again. It seems like the like/unlike toggle is not working and the browser is only sending an 'unlike' request to the server. If the user has never previously like the image, the like/unlike toggle seems to work just fine.
I make use of the post's data attribute to toggle like/unlike requests by making manipulations on these attributes. I'm currently using PHP through a Laravel framework, and jQuery for my front end manipulations.Below is an example of my code.
favorite.js file
$(function(){
$('.favorite-button').click(function(){
var $this=$(this);
var post_id=$this.data('postId');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if($this.data('favoriteId')){
//decrement the favorite count
count=$this.siblings('.favorite-count');
count.html(parseInt(count.html())-1);
//send ajax request
var fav_id=$this.data('favoriteId');
$this.removeData('favoriteId');
$.ajax({
url:'/post/'+post_id+'/favorite/'+fav_id,
type:'DELETE',
success: function(result){
console.log('post was unfavorited');
},
error: function(){
console.log('error: did not favorite the post.');
}
});
}
else{
//update the favorite count
count=$this.siblings('.favorite-count');
count.html(parseInt(count.html())+1);
//send ajax post request
$.ajax({
url:'/post/'+post_id+'/favorite',
type:'POST',
success: function(result){
//update the data attributes
$this.data('favoriteId',result['id']);
console.log(result);
console.log('post was favorited');
},
error: function(){
console.log('error: did not favorite the post.');
}
});
}
});
});
The HTML file
<div class="pull-right">
<span class="marginer">
#if(Auth::guest() || $post->favorites->where('user_id',Auth::user()->id)->isEmpty())
<i data-post-id="{{ $post->id }}" class="fa fa-heart fa-lg favorite-button"></i>
#else
<i data-favorite-id="{{ Auth::user()->favorites()->where('post_id',$post->id)->first()->id }}" data-post-id="{{ $post->id }}" class="fa fa-heart fa-lg favorite-button"></i>
#endif
<span class="favorite-count">{{ $post->favorites->count() }}</span>
</span>
</div>
Aside from solving my issue, if you think I am not conforming with best practices with this task, please do comment. I'd like to hear your opinion.
Instead of trying to make use of jQuery, try to simplify the action of "like/unlike/favorite/count" as much as possible
Avoid querying from blade templates and just send data to the view
Here is how i would approach this problem instead of letting jQuery do the heavy lifting
HTML/rendered
<button class='likebutton' data-identifier='1' data-state='liked'>Like</button>
<button class='favoritebutton' data-identifier='1' data-state='favorited'>Favorite</button>
<span class='count counts-1'>123</span>
Blade
<button class='likebutton' data-identifier='{{!! Post->ID !!}' data-state='{{!! /*<something to see if user liked this>*/?'liked':'unliked' !!}'>{{!! <something to see if user liked>?'liked':'unliked' !!}</button>
<button class='favoritebutton' data-identifier='{{!! Post->ID !!}' data-state='{{!! /*<something to see if user liked>*/?'favorited':'notfavorited' !!}'>{{!! <something to see if user liked>?'favorited':'notfavorited' !!}</button>
<span class='count counts-{{!! $Post->ID !!}}'>{!! $Post->totallikes !!}</span>
JS
$.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
function UserLike(_event){
var state = $(_event.target).data('state');
var postID = parseInt($(_event.target).data('identifier'));
console.log('Status => '+$(_event.target).data('state'));
$.post('/posts/metadata/likes',{
'postID':postID
},function(res){
$(_event.target).data('state',res.state);
$(_event.target).text(res.text);
$('.counts-'+postID).text(res.totallikes);
}).fail(function(){
/* do something on fail */
});
}
function UserFavorite(_event){
var postID = parseInt($(_event.target).data('identifier'));
$.post('/user/metadata/favorites',{
'postID':postID
},function(res){
$(_event.target).data('state',res.state);
$(_event.target).text(res.text);
}).fail(function(){
/* do something on fail */
});
}
$("body").on('click','.likebutton',function(_event){ UserLike(_event); });
$("body").on('click','.favoritebutton',function(_event){ UserFavorite(_event); });
PHP
// Routes
Route::post('/posts/metadata/likes',function(){
// auth check
// handle state/likes
// ex. response
// response with json {'state':notliked,'text':'<translated string>','postID':1}
});
Route::post('/user/metadata/favorites',function(){
// auth check
// handle state/favorites
// response with json {'state':favorited,'text':'<translated string>,'postID':1}
});
I would suggest replacing $this.data('favoriteId'); by $this.attr("data-favourite-id") everywhere. It made the difference for me. check this codepen
http://codepen.io/jammer99/pen/PNEMgV
However I have no idea why your solution does not work
JQuery data('favoriteId') does not set the attribute data-favourite, it's a runtime only setting, it becomes property of the elements, not attrubutes (That's not the same).
Jquery data can hence not be set by server side code.
You can read more it in the jquery doc for .Prop():
http://api.jquery.com/prop/
There's an explanation about the difference.
EDIT: Made the bold sentence!