I have three functions:
function atualizarPublicacoes(){
$.ajax({
url: "{{ path('publicacoes') }}",
type: 'post',
dataType: 'json',
success: function(publicacao){
$.each(publicacao, function(key, value){
$('#mural').append('<div class="border border-light post card my-3"><div id="cabecalho'+value['id']+'" class="px-4 card-header d-flex align-items-center justify-content-between"><div class="d-flex align-items-center"><img class="rounded-circle avatar" style="height:55px ; width:55px" alt="image" src="'+value['userAvatar']+'"></img><div class="mx-3"><div class="text-sm">'+value['userNomeSobrenome']+'<small class="text-muted d-block">'+moment(value['data']).fromNow()+'</small></div></div></div></div><div class="card-body">'+value['post']+'</div><div class="card-footer px-4" style="background-color: #B7BBE0"><div id="acoes'+value['id']+'"></div><div></div></div><div class="card-footer" style="background-color: #CACDE7"><ul class="list-unstyled" id="comentarios'+value['id']+'"></ul></div>');
if(value['titulo']){
$('#cabecalho'+value['id']).append('<h3 class="mb-0" style="font-family: Nunito Sans, sans-serif">'+value['titulo']+'</h3>');
}
if(value['userId'] == "{{app.user.id}}"){
$('#cabecalho'+value['id']).append('<div><button id="editar'+value['id']+'" class="btn btn-gradient-info btn-sm" data-toggle="tooltip" data-placement="top" title="Editar"><i class="mdi mdi-lead-pencil"></i></button><button id="deletar'+value['id']+'" class="ml-2 btn btn-gradient-danger btn-sm" data-toggle="tooltip" data-placement="top" title="Excluir"><i class="mdi mdi-delete-forever"></i></button></div>');
}
});
}
});
};
function atualizarCurtidas(id){
$.ajax({
url: "{{ path('publicacoes_footer')}}",
type: 'post',
datatype: 'json',
success: function(footer){
if(!id){
var footers = footer; //atualiza todos os footers - utilizado quando abre a pagina ou publica um novo post
}else{
var footers = [footer.find(e => e.id == id)]; //atualiza só o footer clicado
}
$.each(footers, function(key, value){
var acoes = $('#acoes'+value['id']);
if( value['curtidas'] != null && "{{ app.user.id }}" in value['curtidas']){
acoes.find('a[title="Comentarios').before('<a title="Curtido" class="ml-2 mr-1" style="cursor:pointer"><i class="icon-md mdi mdi mdi-heart" style="color: #FF4747"></i><small class="mx-1" style="color: #FF4747">'+value['countCurtidas']+'</small></a>');
}else{
acoes.find('a[title="Comentarios').before('{{ form_start(curtir) }}{{ form_widget(curtir._token) }}{{ form_end(curtir, {"render_rest": false}) }}<a title="Curtir" id="'+value['id']+'" class="ml-2 mr-1" style="cursor:pointer"><i class="icon-md mdi mdi mdi-heart-outline" style="color: #FF4747"></i><small class="mx-1" style="color: #FF4747">'+value['countCurtidas']+'</small></a>');
}
});
}
});
};
function atualizarComentarios(id){
$.ajax({
url: "{{ path('publicacoes_footer')}}",
type: 'post',
datatype: 'json',
success: function(footer){
if(!id){
var footers = footer; //atualiza todos os footers - utilizado quando abre a pagina ou publica um novo post
}else{
var footers = [footer.find(e => e.id == id)]; //atualiza só o footer clicado
$('#acoes'+footers[0]['id']).parent().next().find('ul').empty();
}
$.each(footers, function(key, value){
if(value['countComentarios'] > 0){
$('#acoes'+value['id']).append('<a title="Comentarios" class="ml-2 mr-1"><i class="icon-md mdi mdi-comment-processing text-primary"></i><small class="mx-1 text-primary">'+value['countComentarios']+'</small></a>');
$(value['comentarios']).each(function(key, comm){
$('#comentarios'+value['id']).append('<li class="p-2 media rounded mb-2" style="background-color: #E5E6EA ; box-shadow: 0 0 6px gray"><img class="align-self-center mx-2 rounded-circle avatar" style="height:45px ; width:45px" alt="image" src="'+comm['userAvatar']+'"></img><div class="media-body"><h6 class="m-0 text-info">'+comm['userNome']+'<small class="text-muted float-right">'+moment(comm['data']).fromNow()+'</small></h6><small class="mx-2">'+comm['texto']+'</small></div></li>');
$('#comentarios'+value['id']).addClass(value['countComentarios'] > 2 ? '3mais' : '');
})
}else{
$('#acoes'+value['id']).append('<a title="Comentarios" class="ml-2 mr-1"><i class="icon-md mdi mdi-comment-processing-outline text-primary"></i><small class="mx-1 text-primary">0</small></a>');
}
if(!id){
$('#comentarios'+value['id']).after('<div tabindex="-1" class="d-flex justify-content-between align-items-center mx-2 mb-2"><img class="rounded-circle avatar" style="height:45px ; width:45px" alt="avatar" src="{{asset(app.user.avatar)}}"></img><textarea placeholder="'+ (value["countComentarios"] > 0 ?'Escreva seu comentário...' : 'Seja o primeiro a comentar...') +'" class="p-2 mx-1 col-11" maxlength="250"></textarea><a title="Comentar" data-pub="'+value['id']+'" style="cursor:pointer">{{ form_start(comentar) }}{{ form_widget(comentar._token) }}{{ form_end(comentar, {"render_rest": false}) }}<i class="icon-lg mdi mdi-comment-check text-primary"></i></a></div>');
}
});
if(!id){
$('ul.list-unstyled li:nth-child(n+3)').hide();
$('ul.3mais li:nth-last-child(1)').after('<a name="carregar" class="ml-3 text-info" style="cursor:pointer">Carregar mais comentários<i class="mdi mdi-menu-down"></i></a>');
}
}
});
};
and then i call them:
$(document).ready(function(){
moment.locale('pt-BR');
atualizarPublicacoes();
atualizarComentarios();
atualizarCurtidas();
Notiflix.Notify.Init({
position: 'center-top'
});
Notiflix.Confirm.Init({
titleColor: '#ff5549',
okButtonBackground: '#ff5549'
});
});
When I load the page the first one executes but I think that it's finishing after the other 2 finishes because it loads more content (takes more time) so it's like the last two ones didn't executed as they use elements of the previous function to work.
How can I make the second one (AtualizarComentarios) initiate after the first (AtualizarPublicacoes) is completed and the third one after the second?
I call them on other events as well so I can't put them all togheter in one function.
Thanks!
jQuery ajax methods return promise compatible objects, so you could use that. For instance, change the first function to the following -- the key is to use then instead of success and to return the result of the then call:
function atualizarPublicacoes(){
return $.ajax({
//^^^^^^
url: "{{ path('publicacoes') }}",
type: 'post',
dataType: 'json'
}).then(function(publicacao){
// ^^^^^^
$.each(publicacao, function(key, value){
// ... etc ...
});
});
};
Do the same with the other two functions.
In the calling code, either chain then calls, or (simpler) use the async/await syntax:
$(document).ready(async function(){
// ^^^^^
moment.locale('pt-BR');
await atualizarPublicacoes();
//^^^^^
await atualizarComentarios();
await atualizarCurtidas();
Notiflix.Notify.Init({
position: 'center-top'
});
Notiflix.Confirm.Init({
titleColor: '#ff5549',
okButtonBackground: '#ff5549'
});
});
Related
After being searched in the index page, the button action does not work.
While visiting second page the action button does not work.
Here is my index page
<a href="#" class="btn btn-primary btn-active-primary btn-sm"
data-kt-menu-trigger="click" data-kt-menu-placement="bottom-end">
{{actions}}
<span class="svg-icon svg-icon-5 m-0">
<svg xmlns="http://www.w3.org/2000/svg" width="24" </svg>
</span>
</a>
<div class="menu menu-sub menu-sub-dropdown menu-column menu-rounded
menu-gray-600 menu-state-bg-light-primary fw-bold fs-7 w-125px py-4"
data-kt-menu="true">
<div class="menu-item px-3">
<a href="{{ route('index.show', $index->id) }}" class="menu-link
px-3">
{{View Details}}
</a>
</div>
Here is the Route
Route::prefix('example')->name('examples.')->group(function () {
Route::get('', [ExampleController::class, 'index'])->name('index');
});
Here is the script
$(document).on("click", "#pagination a, #search_btn, #reset_btn", function() {
if(this.id == 'reset_btn'){
$("#searchform").reset();
}
$.ajax({
url: this.dataset.url,
type: 'get',
data: $("#searchform").serialize(),
processData: false,
cache: false,
contentType: false,
success: function(data) {
$("#pagination_data").html(data);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
})
});```
Simply solve the bug by inserting the code below into the button function script.
KTMenu.createInstances();
I get the ticket data from a controller using code below:
$.ajax({
type: "GET",
url: "/Tickets/List/",
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
var ds = [];
// d.ticket_no, d.ticket_subject, d.ticket_date,
data.forEach((d) => {
});
}
I don't have an idea on How to display it using the HTML format below?
<a class="list-group-item list-group-item-action" id="list-tickets-list" data-toggle="tab"
href="#ticket-info" role="tab" aria-controls="list-tickets">
<div class="d-flex w-100 justify-content-between">
<h5 id="ticket_subject" class="mb-1">**Ticket Subject Example**</h5>
<small id="ticket_date">**02-Aug-2021**</small>
</div>
<p id="ticket_no" class="mb-1"><strong>**TKT-2021010678**</strong></p>
var data = [{
"ticket_no":1234,
"ticket_subject":"myticker",
"ticket_date":"1-2-3"
},{
"ticket_no":1235,
"ticket_subject":"myticker1",
"ticket_date":"1-2-4"
}];
var mydiv = document.getElementById('ticketdiv');
data.forEach((d) => {
mydiv.innerHTML +=`<a class="list-group-item list-group-item-action" id="list-tickets-list" data-toggle="tab"
href="#ticket-info" role="tab" aria-controls="list-tickets">
<div class="d-flex w-100 justify-content-between">
<h5 id="ticket_subject" class="mb-1">${d.ticket_subject}</h5>
<small id="ticket_date">${d.ticket_date}</small>
</div>
<p id="ticket_no" class="mb-1"><strong>${d.ticket_no}</strong></p>`
});
<div id="ticketdiv">
</div>
you can use JS innerHTML to get it done, here what I'm doing is looping the data from foreach, and adding HTML content to the div by mydiv.innerHTML +=
you can read more about JS innerHTML here
I'm using ajax to make a request and open a modal bootstrap window afterwards. The problem is that when I use ajax, I make a request to my controller, and the return (modal content) I load as follows:
//modal loading
$('#contentModalFinanceiroParcela').html(data);
//exibição da modal
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
So far, everything perfect. The problem is that from then on, I can't bind the form to register the submit event of the form. In the function bindFormFinanceiroParcela, no matter how much I pass the "dialog", bind does not work.
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
Searching the forums, I found that the process works if I load the modal using the "load" command, as below, but I can't do it like that, otherwise it will make a second request to the controller, because previously, I already used ajax .
//That way it works, but I can't use it.
$('#contentModalFinanceiroParcela').load(url, function () {
$('#modalFinanceiroParcela').modal({
keyboard: true
}, 'show');
// Inscreve o evento submit
bindFormFinanceiroParcela(this);
stopLoadPage();
});
Is there a possibility that I can bind the form without using the "load" command mentioned in the script above?
function openModalFinanceiroParcelaSemURL(data) {
startLoadPage();
//Create the modal window block in the body of the page
if (!$("#modalFinanceiroParcela").data('bs.modal'))
CreateModalFinanceiroParcela();
//Load modal content via ajax request
$('#contentModalFinanceiroParcela').html(data);
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
stopLoadPage();
}
function bindFormFinanceiroParcela(dialog) {
$('form', dialog).submit(function (e, i) {
if ($(this).valid() || i) {
startLoadOneMoment();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
window.location = window.location;
} else {
$('#contentModalFinanceiroParcela').html(result);
bindFormFinanceiroParcela();
}
stopLoadOneMoment();
}
});
return false;
} else {
return false;
}
});
function CreateModalFinanceiroParcela() {
var html = '<div class="modal modal-primary modal-system" tabindex="-1" role="dialog" id="modalFinanceiroParcela" data-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="content-modal-system" id="contentModalFinanceiroParcela"></div></div></div></div>';
$("body").append(html);
}
RAZOR DELETE:
#using Retaguarda.Domain.Enuns
#model Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela.FinanceiroParcelaViewModel
#{
ViewData["Title"] = "Excluir Parcela";
Layout = null;
}
<div>
<form asp-action="Delete" id="frm-excluir-financeiro-parcela">
#Html.AntiForgeryToken()
<div class="modal-shadow">
<div class="modal-header modal-header-primary">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4><i class="modal-title text-center glyphicon glyphicon-trash"></i> #ViewData["Title"] </h4>
</div>
<div class="panel">
<div class="panel-body container-fluid pt-15 pl-15 pr-15">
<div class="form-horizontal">
<vc:summary />
<br />
<div class="message-delete">
#Html.HiddenFor(model => model.Id, new { id = "hid-financeiro-parcela-id" })
<i class="icon fa-trash" aria-hidden="true"></i>
<p>
Tem certeza de que deseja excluir a parcela #(Model.Parcela)?<br />
</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-md-offset-2 col-md-10">
<div class="float-right">
<div class="btn-group btn-group-sm mr-auto"
role="group">
<div class="btn-group btn-group-sm" role="group">
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
<button id="btn-excluir-financeiro-parcela" type="button" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>
<button id="btn-cancelar-financeiro-parcela" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Ajax call
$('#dtFinanceiroParcela').on('click', 'tr .btn-excluir-financeiro-parcela', function (e) {
e.preventDefault();
startLoadOneMoment();
var id = $(this).attr('data-id');
var data = { id: id };
var dataURL = jQuery.param(data);
$.ajax({
url: "/financeiro-parcela-gerenciar/remover-financeiro-parcela/" + id,
type: "GET",
// data: dataURL,
contentType: "application/json",
async: false,
success: function (result) {
if (typeof result.success !== 'undefined') {
if (!result.success) {
stopLoadOneMoment();
swal("Oops", result.message, "error");
return false;
}
}
// alert(this.url);
stopLoadOneMoment();
openModalFinanceiroParcelaSemURL(result);
return false;
},
error: function () {
stopLoadOneMoment();
alert("Oops! Algo deu errado.");
return false;
}
});
Your form inside razor does not contain any submit button because its commented out.
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
Remove the comment or change the type of the other button to "submit"
I guess the submit event is attached successfully but never called due to the missing submit button inside your form.
With jQuery v3.2, I want to extract and remove "H1" from AJAX data :
$('.version-modal-show').click(function() {
var url = $(this).attr('href');
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success:function(d) {
console.log(d);
modal.setBody(d);
modal.open();
}
});
return false;
});
console.log(d) return html brut :
<h1>
<i class="fa fa-list" aria-hidden="true"></i>
Centre d'intérêt « TESTb »
</h1>
<p class="text-center">
<a href="/app_dev.php/administration/hobbies" class="btn btn-secondary">
<i class="fa fa-backward" aria-hidden="true"></i>
Retour aux centres d'intérêts
</a>
</p>
I want to remove the h1 from the modal.setBody() but put it in the modal.setTitle()
You can set the .filter()ed content
modal.setTitle($(d).filter('h1').prop('outerHTML'));
modal.setBody($(d).filter('p.text-center').prop('outerHTML'));
i have a comment system on my app in laravel and i can edit my comments with ajax but once edited it doesn't load automatically the edited comment. To see the edited comment i need to reload the page manually. I will put some of the code here.
This is the JS:
var commentId = 0;
var divcomment = null;
$('.edit-comment').click(function(event){
event.preventDefault();
/* Accedemos al Div Que contiene el Panel*/
var divcomment = this.parentNode.parentNode;
/* Buscamos el Contenido con Id display-text */
commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
var commentBody = $(divcomment).find('#display-comment').text();
$('#comment').val(commentBody);
$('#edit-comment').modal();
/* Asignas a tu modal */
});
$('#modal-save').on('click', function(){
$.ajax({
method: 'PUT',
url: urlEdit,
data: {
comment: $('#comment').val(),
commentId: commentId,
_token: token,
_method: 'PUT',
dataType: 'json',
}
})
.done(function (msg){
$(divcomment).text(msg['new_comment']);
$('#edit-comment').modal('hide');
});
});
This is the Html:
<article class="row">
<div class="col-md-3 col-sm-3 hidden-xs">
<figure class="thumbnail">
<img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic }}" />
<figcaption class="text-center">{{ $comment->user->name }}</figcaption>
</figure>
</div>
<div class="col-md-8 col-sm-8">
<div class="panel panel-default arrow left">
<div class="panel-body">
<header class="text-left">
<div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
<time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
</header>
<div id="comment-post" data-commentid="{{ $comment->id }}">
<p id="display-comment">{{ $comment->comment }}</p>
</div>
</div>
<div class="panel-footer list-inline comment-footer">
#if(Auth::guest())
No puedes responder ningún comentario si no has ingresado.
#else
#if(Auth::user() == $comment->user)
Editar Eliminar
#endif
#if(Auth::user() != $comment->user)
Responder
#endif
#endif
</div>
</div>
</div>
</article>
2 variables created on the view
var token = '{{ Session::token() }}';
var urlEdit = '{{ url('comments/update') }}';
and finally the modal where i edit the comment:
<div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="comment">Editar comentario</label>
<textarea class="form-control" name="comment" id="comment"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
<button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
</div>
</div>
</div>
</div>
Everything's working but the only thing i need is to load the edited comment back without refresh the whole page, btw i used $('#display-comment').load(document.URL + ' #display-comment'); and with this line i succesfully load the edited comment but, it load all the comments on the edited one, so i have to refresh the whole page to show just the edited.
Assuming that the data sent to the php side of things is the same data that you then want to update to, the following should work:
$('#modal-save').on('click', function(){
var comment = $('#comment').val();
// shove the edited comment into a variable local to the modal handler
$.ajax({
method: 'PUT',
url: urlEdit,
data: {
comment: comment, // reference said variable for ajax data
commentId: commentId,
_token: token,
_method: 'PUT'
},
dataType: 'json'
})
.done(function (msg){
//$(divcomment).text(msg['new_comment']);
// I commented out the above line as it clears the
// divcomment div's text entirely.
// Comment out the below 'if check' if it is not needed.
if (msg.success === true) {
$(divcomment).find('#display-comment').text(comment);
// And overwrite the #display-comment div with the new
// data if the user was successful in editing the comment
}
$('#edit-comment').modal('hide');
});
});
In a previous question of yours, you had a controller method on the php side of things that handled the ajax. Instead of redirecting(since it is ajax, there is no redirect), you should instead return json to indicate whether the action was successful or not. Here is an example of that:
public function update(Request $request)
{
//...
$comment = Comment::find($request['commentId']);
if (Auth::user() != $comment->user) {
return response()->json(['success' => false], 200);
}
//...
return response()->json(['new_comment' => $comment->comment, 'success' => true], 200);
}
I referenced the above json in my answer on the javascript side of things; if you are not going to use the json response, then simply comment out the line(as I also noted in the code).
Update:
I missed something in your earlier block of code; you declare divcomment outside of the edit link's handler, but then you re-declare it inside of that handler again. I missed this in my earlier answer, so simply deleting the var from it, so it uses the outside declaration, fixes your code:
var commentId = 0;
var divcomment = null; //this is already declared, no reason to declare it
// again
$('.edit-comment').click(function(event){
event.preventDefault();
/* Accedemos al Div Que contiene el Panel*/
divcomment = this.parentNode.parentNode;
// ^ remove the var, making this use the global variable you already
// made above
/* Buscamos el Contenido con Id display-text */
commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
var commentBody = $(divcomment).find('#display-comment').text();
$('#comment').val(commentBody);
$('#edit-comment').modal();
/* Asignas a tu modal */
});