Ajax / JQuery - Displaying flash message on success - javascript

I have a fully working flash system in PHP and am using it to send the user a success message once I create an entry in the DB.
On one of my forms I have a select field which I want the user to be able to seamlessly add entries too it without directing them away from a semi-completed form. The code I'm using is working well. The user clicks on 'add a category' (in the select label) it opens a modal, the user creates a new category, it updates the DB and the select field and closes the modal using AJAX. All working.
What I need to do is use or adapt my flash system to give the user a message to say all good your entry was added. I am very new to AJAX and on a steep learning curve!
This is my AJAX / JQUERY code: (I followed a tutorial to get here. The idea is to make this usable across the site when I need to add entries to a select, by adding 'ajax' to the form class.)
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index,value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$('#select').load(document.URL + ' #select');
$('#addCategoryModal').modal('hide');
$('#siteMessage').toast('show');
}
});
return false;
});
And this is the PHP setting the DB record (working) and how I normally trigger a flash message on page reload (messages also work):
//create record in db
$newCategory = $this->blogModel->createCategory($formFields);
if ($newCategory) {
flash('siteMessage', 'Blog category added successfully');
} else {
flash('siteMessage', 'Something went wrong', 'bg-danger');
}
And this is the flash code:
function flash($name = '', $message = '', $class = 'bg-success') {
if (!empty($name)) {
if (!empty($message) && empty($_SESSION[$name])) {
if (!empty($_SESSION[$name])) {
unset($_SESSION[$name]);
}
if (!empty($_SESSION[$name.'_class'])) {
unset($_SESSION[$name.'_class']);
}
$_SESSION[$name] = $message;
$_SESSION[$name.'_class'] = $class;
} elseif (empty($message) && !empty($_SESSION[$name])) {
$class = !empty($_SESSION[$name.'_class']) ? $_SESSION[$name.'_class'] : '';
echo '
<div id="siteMessage" class="toast shadow" data-delay="8000" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 19px; right: 45%; z-index:10">
<div class="toast-header '.$class.'">
<i class="fas fa-envelope mr-2 pt-1 text-white"></i>
<strong class="mr-auto text-white">Site Message</strong>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span class="text-white" aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
'.$_SESSION[$name].'
</div>
</div>
';
unset($_SESSION[$name]);
unset($_SESSION[$name.'_class']);
}
}
}
My PHP processing page, creates the entry in the DB and I set the flash message as normal. I think I don't understand the interaction with how AJAX gets the returned success and setting a flash message.
Any thoughts?

Thanks to CBroe who pointed out the inherent problems with using a flash message mechanism I've added the following div at the bottom of the page and am now calling that direct with toast.show to give the message to the user.
I am not sure if that is the most affective way to do this but it works.
<div id="categoryMessage" class="toast shadow" data-delay="8000" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 19px; right: 45%; z-index:10">
<div class="toast-header bg-success">
<i class="fas fa-envelope mr-2 pt-1 text-white"></i>
<strong class="mr-auto text-white">Site Message</strong>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span class="text-white" aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
The category was added successfully
</div>
</div>

Related

Blazor, Image from Graph API not loading without refreshing

In my Blazor app when I user signs in (through Azure AD) I am using an async Graph API call to retrieve their profile picture and display it in the top bar.
The problem is it only loads after a window refresh.
To try to load it after I re-run the async method when they click login, since the OnInitializedAsync() runs before they sign in as well then, the loginDisplay view is first rendered.
after converting the picture to a Base64String I then check if the string is not empty (result of null or a failed conversion for the method I wrote) and try o display the image:
#if (userPhoto != string.Empty)
{
<div class="col-md-auto align-self-center position-relative">
<a #onclick="() => userMenu()">
<img id="mePicture" class="rounded-circle" src="#userPhoto" style="width: 45px; height: 45px;" />
</a>
#if (renderUserMenu)
{
<div class="container-fluid position-absolute top-0 end-50 border-1 p-2 border-dark shadow bg-light rounded bg-dark" style="width: 120px;" #onblur="() => userMenu()">
<button class="btn btn-sm btn-outline-secondary m-0 p-0 shadow-sm" style="height: 20px; width: 20px;" #onclick="() => userMenu()">X</button>
<div class="text-center align-content-center">
<img class="rounded-circle" src="#userPhoto" style="width: 65px; height: 65px;"/>
<button class="btn btn-sm btn-outline-secondary shadow-sm" #onclick="BeginLogout">Log out</button>
</div>
</div>
}
</div>
}
else
{
<div class="col-md-auto align-self-center">
<div class="rounded-circle" style="width: 45px; height: 45px;"> #initials</div>
<img class="rounded-circle" src="#userPhoto" style="width: 45px; height: 45px;" />
</div>
}
I don't know how to force it to render after the async method fetches it.
My guess is that the LodingDisplay.razor partial doesn't refresh after login in.
I tried using JS to load it (didn't fail, but didn't render it)
Also tried a secondary function on the #onclick event of the login button also to no effect.
Any help appreciated.
Relevant C# Code:
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var _user = authState.User;
if (_user.Identity.IsAuthenticated)
{
claims = _user.Claims;
var request = GraphClient.Me.Request();
user = await request.GetAsync();
await GetMePhotoAsync();
authMessage = "";
}
}
private async Task GetMePhotoAsync()
{
var photo = await GraphClient.Me.Photo.Content.Request().GetAsync();
byte[] bytes;
using (var memoryStream = new MemoryStream())
{
photo.CopyTo(memoryStream);
bytes = memoryStream.ToArray();
}
var photoString = Convert.ToBase64String(bytes);
userPhoto = string.Format("data:image/jpeg;base64,{0}", photoString);
var uid = user.Id;
var displayName = user.DisplayName;
var displayNameList = displayName.Split(" ").ToList();
if (displayNameList.Count > 1)
{
initials = displayNameList[0].Substring(0) + displayNameList[1].Substring(0);
}
else
{
initials = displayName.Substring(0, 1);
}
}

Jquery strange chaining of Ajax requests

I have a div called project and it is rendered with EJS
There several projects in the data for EJS, they are rendered by forEach loop - so several similar div appear.
The project div has id for identification in Jquery.
Further it has a project.name and project.id as a data-*
The problem which I encountered:
If I don't reload the page as intended - first try works well and Element inner text get updated correctly.
But on second try to change another project name both are changed to value of previous, so to say for both projects. In few words - new change overrides all previous. How is it possible?
Link to see how it looks in GIF
Imgur
Strange behaviour of chaining requests Imgur
<%userData.forEach(function(project){%>
<div class="project" id='project <%=project.id%>'>
<div class="projectHeader">
<div class="projectTitle">
<h5 id="projectTitle <%=project.id%>" class="projectName">
<%=project.name%>
</h5>
<div class="projectButtons">
<span data-toggle="tooltip" data-placement="top" title="Edit Project Title">
<a data-toggle="modal" data-target="#editProjectTitleModal">
<i id="editProjectName" class="editProject fas fa-pencil-alt"
data-name="<%=project.name%>" data-id="<%=project.id%>"></i>
</a>
</span>
</div>
</div>
</div>
A simple modal is called when the a tag in project is clicked.
<div class="modal fade" id="editProjectTitleModal" tabindex="-1" aria-labelledby="exampleformModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form class="" action="" method="">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Title</h5>
</div>
<div class="modal-body">
<div class="input-group">
<input id="editProjectNameInput" autocomplete="off" pattern="[a-zA-Z0-9 ].{1,25}" title="1 to 25 characters" class="form-control" aria-label="With textarea" placeholder="Enter new title" required></input>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="confirmEditProjectName" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
Jquery event handler which serves to change project.name, at first sends it to database and ammend DOM with new name. So the database get the new data, but the page is not reloaded and project.name changed simultaneously.
It grabs project-name and project-id and sends Ajax regular post - method, on success - change element's inner text to project-name
// Edit Project Title by ID
$(document).on('click', "#editProjectName", function() {
//Grab Id of the Project
var editProjectId = $(this).attr('data-id');
//Fill Modal input with current project.name
var currentTitle = document.getElementById('projectTitle ' + editProjectId).innerText;
$("#editProjectNameInput").val(currentTitle)
var url = '/editProjectName';
$('#confirmEditProjectName').on('click', function(event) {
//Take new project name from updated modal input
var newTitle = $("#editProjectNameInput").val();
//If they are same - alert
if (currentTitle === newTitle) {
event.preventDefault();
alert("New Title should be different")
} else {
event.preventDefault();
if (newTitle.length > 1 && newTitle.length <= 25) {
$.ajax({
type: "POST",
url: url,
data: {
projectName: newTitle,
projectID: editProjectId
},
success: function(result) {
//Hide modal and change element inner text to new value
$("#editProjectTitleModal").modal('hide')
document.getElementById('projectTitle ' + editProjectId).innerText = newTitle;
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
I removed the space from the IDs and I changed from using the ID of #editProjectName to just using the class that is already on that object of editProject.
<%userData.forEach(function(project){%>
<div class="project" id='project<%=project.id%>'>
<div class="projectHeader">
<div class="projectTitle">
<h5 id="projectTitle<%=project.id%>" class="projectName">
<%=project.name%>
</h5>
<div class="projectButtons">
<span data-toggle="tooltip" data-placement="top" title="Edit Project Title">
<a data-toggle="modal" data-target="#editProjectTitleModal">
<i class="editProject fas fa-pencil-alt"
data-name="<%=project.name%>" data-id="<%=project.id%>"></i>
</a>
</span>
</div>
</div>
</div>
// Edit Project Title by ID
$(document).on('click', ".editProject", function() {
//Grab Id of the Project
var editProjectId = $(this).attr('data-id');
//Fill Modal input with current project.name
var currentTitle = document.getElementById('projectTitle' + editProjectId).innerText;
$("#editProjectNameInput").val(currentTitle)
var url = '/editProjectName';
$('#confirmEditProjectName').on('click', function(event) {
//Take new project name from updated modal input
var newTitle = $("#editProjectNameInput").val();
//If they are same - alert
if (currentTitle === newTitle) {
event.preventDefault();
alert("New Title should be different")
} else {
event.preventDefault();
if (newTitle.length > 1 && newTitle.length <= 25) {
$.ajax({
type: "POST",
url: url,
data: {
projectName: newTitle,
projectID: editProjectId
},
success: function(result) {
//Hide modal and change element inner text to new value
$("#editProjectTitleModal").modal('hide')
document.getElementById('projectTitle' + editProjectId).innerText = newTitle;
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
After some research I have found out that once the on('click') is called it is On until the page get reloaded.
Thanks to this Question and Answer:
https://stackoverflow.com/a/6121501/13541013
I figured out - on('click') event should be switched off by calling $(this).off() (this is the event)
In my case I had to make $(this).off() right after:
$(document).on('click', "#editProjectName", function() {
$(this).off() ... further code
And it has to be done for every single on('click') event in the script.

I want to be able to edit data given in my foreach

On my site I'm building my own kind of blog for the users and would like for the comments that people place under the posts to be editable. Unfortunately I haven't been able to get this far with it. Because they all have the same class/id.
I've tried using data-id, but I'm not really adept when it comes to those. Other than that I've searched for ages, but couldn't really find anything that could help me with the code I have.
Function that gets the post and comments:
public function announcement(Announcement $announcement)
{
$announcements = Announcement::findOrFail($announcement->id);
$category_lists = Category::withCount('posts')->get();
$replies = Reply::where('post_id', $announcement->id)->paginate(5);
return view('announcements.details', compact('announcements', 'category_lists', 'replies'));
}
The comment foreach:
#foreach($replies as $reply)
<div class="announcement">
#if(Auth::user()->admin == 1 || Auth::user()->id == $reply->user_id)
<i class="fal fa-dumpster"></i>
#endif
#if(Auth::user()->id == $reply->user_id)
<i class="fal fa-pencil float-right" id="yeet" class="float-right showhidereply" style="color: #007ac3; margin-right: 10px;" data-id="{{ $reply->id }}"></i>
#endif
<p style="font-size: 0.8rem;">{{$reply->created_at->diffForHumans()}} | Geplaatst door <span>{{$reply->username}}</span></p>
<p style="margin-top: -10px;">{!! $reply->post_content !!}</p>
#if(Auth::user()->id == $reply->user_id)
<div class="reply-expand-{{$reply->id}}" style="display: none;">
<form method="POST" action="{{ route('Reply Edit', ['id' => $reply->id]) }}">
#csrf
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Reactie Aanpassen:</strong>
<textarea class="form-control summernote" name="detail">{!! $reply->post_content !!}</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary pull-right" style="border-radius: 0px; box-shadow: 0px 1px 10px -4px #000000;">Aanpassen</button>
</div>
</form>
</div>
#endif
<hr>
</div>
#endforeach
Editting function:
public function postSummernoteeditorReply(Request $request, $id){
$this->validate($request, [
'detail' => 'required',
]);
$detail=$request->detail;
$dom = new \DomDocument();
$dom->loadHtml( mb_convert_encoding($detail, 'HTML-ENTITIES', "UTF-8"), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $img){
$src = $img->getAttribute('src');
// if the img source is 'data-url'
if(preg_match('/data:image/', $src)){
// get the mimetype
preg_match('/data:image\/(?<mime>.*?)\;/', $src, $groups);
$mimetype = $groups['mime'];
// Generating a random filename
$filename = uniqid();
$filepath = "/img/blog/$filename.$mimetype";
// #see http://image.intervention.io/api/
$image = Image::make($src)
// resize if required
/* ->resize(300, 200) */
->encode($mimetype, 100) // encode file to the specified mimetype
->save(public_path($filepath));
$new_src = asset($filepath);
$img->removeAttribute('src');
$img->setAttribute('src', $new_src);
} // <!--endif
} // <!--endforeach
$detail = $dom->saveHTML();
$summernote = Summernote::find($id);
$summernote->post_content = $detail;
//dd($summernote->post_content);
//dd($summernote->post_id);
$summernote->update();
return redirect(url()->previous());
}
JQuery to show the editting form:
$(document).ready(function() {
$('.summernote').summernote({
height: 400,
});
$('#yeet').click(function() {
$('.reply-expand').toggle("slide");
});
// change the selector to use a class
$("#yeet").click(function(){
// this will query for the clicked toggle
var $toggle = $(this);
// build the target form id
var id = "#replycomment-" + $toggle.data('id');
$( id ).toggle('slide');
});
});
The expected outcome should be to be able to edit each comment individually by clicking on the edit icon(pencil) next to the comment and having the form show before being able to edit. I already have the edit function and displaying the form working, but only for the first comment.
I hope someone will be able to help! Many thanks!
EDIT: When I click the edit button on the first comment, it opens the form with the data of the second/last comment, but clicking the second/last edit button doesn't do anything.
First have a unique Id for the clickable items. Right now they all have the same id (yeet) and that could be the cause of the problem.
<i class="fal fa-pencil float-right yeet" id="yeet-{{ $reply->id }}" class="float-right showhidereply" style="color: #007ac3; margin-right: 10px;"></i>
We can keep yeet as a class to handle the click events for all the comments. This way each comment will have a different Id and they will all go through the same click event.
Now change the selectors to use the yeet class intead of the id.
$('.yeet').click(function() {
//get the clicked element id and toggle the respective form
}
You have to add unique ids to the form in the same way as before to be able to toggle each one independently.

PHP - Submit button and Modal Pop-up AJAX on 2 browsers PHP

I am new to php AJAX coding, my problem is I have TWO BROWSERS, first is I want to click the submit button and after that I want a modal to popup on the other browser so the final output will be a 2 browsers. just like a chat system. but it is different because I only want a button and a pop up modal.
so for example here is my button
<button type="button" class="btn btn-primary">CLICK TO POPUP</button>
My Modal
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
How can I popup this modal to the other localhost browser
Concurrent snapshots with php socket, you can run the results in all open windows.
PHP Socket
WebSocket
A simpler method is also controlled by ajax, which records the operation in a database every second, and popUp is shown with data from ajax if it needs to be shown in popUp.
But not a highly recommended method
Click Button
$.ajax({ url: "saveClickButton.php" })
setTimeout(function() {
$.ajax({ url: 'isClickButton' }).done(function(data) {
if ( data === "true" ) {
// Open Pop Up
}
});
}, 1000)
First, we are writing the listener in a php file.
then it writes a javascript process that will get the listener to tap and get feedback.
I'm sending the socket e 'getOpenPopUp' message that we're connected to with javascript. The socket on the php side is sending the openPopUp message to all clients after verifying it. this message is received on the javascript side popUp opens. my English is not good at all. I'm sorry I couldn't tell.
socket.php - Ratchet Class Ratchet
<?php
require __DIR__.'/vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class Application implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
if ( $msg === 'getOpenPopUp' ) {
foreach ($this->clients as $client) {
$client->send('openPopUp');
}
}
}
public function onClose(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, \Exception $e) {
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Application()
)
),
8080
);
$server->run();
App.js - WebSocket MDN Writing WebSocket client applications
var socket = new WebSocket('ws://localhost:8080');
var button = document.getElementById('button');
button.addEventListener('click', function() {
console.log('click')
socket.send('getOpenPopUp');
});
socket.onmessage = function(e) {
console.log(e)
if ( e.data === 'openPopUp' ) {
UIkit.modal.confirm('UIkit confirm!');
}
}

How to load specific div or id ajax and laravel

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 */
});

Categories