I make Comment by Ajax but its not working - laravel

I make Comment by Ajax but its not working. It can insert and I already recived the data form controller. I check alert is display but html not display.
Here is my Route: Route::post('/addComment', 'LessonController#addComment');
Here is my controller
public function addComment(Request $request)
{
$lesson_id = $request->lesson_id;
$name = $request->name;
$body= $request->body;
$comment = new Comment();
$comment->name = $name ;
$comment->body = $body;
$comment->lesson_id = $lesson_id;
$comment->save();
return response()->json($comment);
}
Here is view comment create
<div class="leave_review">
<h3 class="blog_heading_border"> Leave a Comment </h3>
{!! Form::open(['action' => 'LessonController#addComment', 'method' => 'POST', 'id' => 'comment' ]) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="hidden" id="lesson_id" name="lesson_id" value="{{$lesson->id}}" />
</div>
<div class="row">
<div class="col-sm-6">
{{Form::label('name','Name')}}
{{Form::text('name', '', ['class' => 'form-group', 'id'=>'name']) }}
</div>
<div class="col-sm-12">
{{Form::label('body','Message')}}
{{Form::textarea('body', '', ['class' => 'form-group', 'id'=>'body']) }}
</div>
</div>
<div class="row">
<div class="col-md-12">
</div>
</div>
{{Form::submit('Submit', ['name'=>'submit', 'class' => 'mt_btn_yellow pull-right'])}}
{!! Form::close() !!}
<br>
Here is comment display view blade
<div id="commen_show">
#foreach ($comment as $item)
<ol class="review-lists">
<li class="comment">
<div class="activity_rounded">
<img src="/storage/Iconimage/about.png" alt="image"> </div>
<div class="comment-body">
<h4 class="text-left">{{$item->name}}
<small class="date-posted pull-right">{{$item->created_at}}</small>
</h4>
<p>{{$item->body}}</p>
Reply
<div class="clearfix"></div>
</div>
</li>
</ol>
#endforeach
</div>
</div>
Here is my javascript, I think something wrong with append
<script>
$(document).ready(function($){
$('#comment').on('submit', function(){
var lesson_id = $('#lesson_id').val();
var name = $('#name').val();
var body = $('#body').val();
var _token = $('input[name="_token"]').val();
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : "{{url('/addComment')}}", // the url where we want to POST
data: {_token:_token, lesson_id:lesson_id, body:body, name:name},
success: function(response) {
if(response){
$('#commnet_show').prepend(
` <ol class="review-lists">
<li class="comment">
<div class="activity_rounded">
<img src="/storage/Iconimage/about.png" alt="image"> </div>
<div class="comment-body">
<h4 class="text-left">${response.name}
<small class="date-posted pull-right">${response.created_at}</small>
</h4>
<p>${response.body}</p>
Reply
<div class="clearfix"></div>
</div>
</li>
</ol> `
;);
}
}
});
});
});
</script>

Related

Laravel 8 Dynamic Dependent Input

it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212
i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);
Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>

Laravel view load twice to display comment

I don't know why the page has to load twice to display comments.
Here is my route: Route::post('/addComment', 'CommentsController#addComment');
Here is my controller:
public function addComment(Request $request)
{
$this->validate($request, [
'name' => 'required',
'body' => 'required',
]);
$lesson_id = $request->lesson_id;
$comment = new Comment;
$comment->name = $request->input('name');
$comment->body = $request->input('body');
$comment->parrent_id = '0';
$comment->lesson_id = $request->lesson_id;
$comment->save();
return back();
}
Here is my view:
<div class="leave_review">
<h3 class="blog_heading_border"> コメント </h3>
{!! Form::open(['action' => ['CommentsController#addComment'], 'method' => 'POST', 'id' => 'postForm' ]) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="hidden" id ="lesson_id" name="lesson_id" value="{{$lesson->id}}" />
</div>
<div class="row">
<div class="col-sm-6">
#error('name')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
{{Form::label('name','名前')}}
{{Form::text('name', '', ['class' => 'form-group', 'id' => 'name' ]) }}
</div>
<div class="col-sm-12">
#error('body')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
{{Form::label('body','メッセージ')}}
{{Form::textarea('body', '', ['class' => 'form-group', 'id' => 'body']) }}
</div>
</div>
<div class="row">
<div class="col-md-12">
</div>
</div>
{{Form::submit('Submit', ['class' => 'send mt_btn_yellow pull-right', 'id' => 'submit'])}}
{!! Form::close() !!}
{{-- End add comment --}}
{{--Display comment--}}
<ol class="review-lists">
#foreach ($comment as $value)
<li class="comment">
<div class="activity_rounded">
<img src="/storage/icon/icon.jpg" alt="image"> </div>
<div class="comment-body">
<h4 class="text-left">{{$value->name}}
<small class="date-posted pull-right">{{ \Carbon\Carbon::parse($value->created_at)->diffForHumans() }}</small>
</h4>
<p>{{$value->body}} </p>
<button class="pull-left mt_btn_yellow" onclick="toggleReply('{{$value->id}}')">返事</button>
{{-- ENd Display comment--}}
#foreach ($comment as $value)
<li class="comment">
<div class="activity_rounded">
<img src="/storage/icon/icon.jpg" alt="image"> </div>
<div class="comment-body">
<h4 class="text-left">{{$value->name}}
<small class="date-posted pull-right">{{ \Carbon\Carbon::parse($value->created_at)->diffForHumans() }}</small>
</h4>
<p>{{$value->body}} </p>
<button class="pull-left mt_btn_yellow" onclick="toggleReply('{{$value->id}}')">返事</button>
{{-- ENd Display comment--}}
you don't have a #endforeach

Laravel - How to Pass a variable to controller and to url name of route

I need to pass variable to controller of details of Boat and show it in the url.
This is the blade view where I download a list of boats available:
#foreach($Boats as $boat)
<article class="box">
<figure class="col-sm-4">
<a title="" href="{{asset('frontend')}}/ajax/cruise-slideshow-popup.html" class="hover-effect popup-gallery"><img width="270" height="160" alt="" src="{{ json_decode($boat->images, true)['url']}}"></a>
</figure>
<div class="details col-sm-8">
<div class="clearfix">
<h4 class="box-title pull-left">{{$boat->name}}<small>{{$boat->id}}</small></h4>
<span class="price pull-right"><small>from</small>$239</span>
</div>
<div class="character clearfix">
<div class="col-xs-3 cruise-logo">
<img src="http://placehold.it/110x25" alt="" />
</div>
<div class="col-xs-4 date">
<i class="soap-icon-clock yellow-color"></i>
<div>
<span class="skin-color">Date</span><br>{{$boat->year}}
</div>
</div>
<div class="col-xs-5 departure">
<i class="soap-icon-departure yellow-color"></i>
<div>
<span class="skin-color">Departure</span><br>{{$boat->homeBase}}
</div>
</div>
</div>
<div class="clearfix">
<div class="review pull-left">
<div class="five-stars-container">
<span class="five-stars" style="width: 60%;"></span>
</div>
<span>270 reviews</span>
</div>
select cruise
</div>
</div>
</article>
#endforeach
This is route route.php file to translate url:
return [
"login" => "login",
"register" => "register",
"listBoats" => "boats",
"contact" => "contact",
"detailedBoat" => "DetailBoat/{id}",
];
web.php :
Route::get(LaravelLocalization::transRoute('routes.detailedBoat'),('DetailedBoat'), function (\App\Boat $id) {
return $id;
});
DetailsBoat Controller:
public function __invoke($id)
{
echo $id;
return view('frontendViews.detailedBoat');
}
Result should be
http://localhost:8000/en/boats/{id}
The strange thing is that routes work perfectly based on app.php 'locale' setting, if i have 'en' i get http://localhost:8000/en/DetailBoat/1` and http://booking:8888/it/DettaglioBarca/%7Bid%7D switching language;
viceversa if have ['it'] on app.php i'm getting http://booking:8888/it/DettaglioBarca/1 and http://booking:8888/en/DetailBoat/%7Bid%7D in english.
Thank you

Laravel/VueJs. How can I display button with different color based on column value passed in?

I'm looping through user table. And each user table has a button that toggle(update:Boolean type) user status on user table. And I want the button for each user to have red color when the status value for the user is 0 and green when the status is 1. Also I want the button to change the color(LIVE) based on the status value each time it clicked.
component: ToggleStatus.vue
<template>
<div>
<button type="button" v-bind:class="buttonStatus" #click="goOnline">
<span class="ion-ios-wifi" ></span>
</button>
</div>
</template>
<script>
export default {
props: ['userId', 'onlinestat'],
mounted() {
console.log('Component mounted.')
},
data: function() {
return {
status: this.onlinestat,
}
},
methods: {
goOnline() {
axios.post('/reservation/online/' + this.userId )
.then(response => {
this.status =! this.status;
console.log(response.data);
})
.catch(errors => {
if (errors.response.status == 401){
window.location = '/login';
}
});
}
},
computed: {
buttonStatus() {
return(this.status) ? 'btn btn-outline-danger text-danger' : 'btn btn-success ';
}
}
}
</script>
Controller:
$authUser = Auth::user()->business_id;
$employee = User::where('business_id', $authUser)->get()->sortBy('name');
return view('backend.reservation.index', compact('employee'));
View/Blade
<div class="container-fluid flex-grow-1 container-p-y">
<div class="uikit-example">
<div class="row">
#foreach ($employee as $key => $emp)
<div class="col-lg-4 col-md-4 col-sm-12">
<div class="card mb-4">
<div class="card-body">
<div class="media align-items-center">
<img src="{{ asset('Upload/Images/Media/Avatar/Thumb/'.$emp->image) }}" alt class="ui-w-60 rounded-circle">
<div class="media-body pt-2 ml-3">
<h5 class="mb-2">{{ $emp->name }}</h5>
<div class="text-muted small mb-2">{{ $emp->phone }}</div>
<div class="text-muted small mb-2">{{ $emp->email }}</div>
<div class="text-muted small mb-2"><span>ID: </span>{{ $emp->user_code }}</div>
</div>
<div class="">
<toggleonline user-id="{{ $emp->id }}" onlinestat="{{ $emp->onlinestatus }}"></toggleonline>
</div>
</div>
</div>
<div class="card-footer text-center py-3">
{{-- + Go Online --}}
{{-- <span class="ion ion-md-mail"></span> --}}
{{-- <div class="float-right"> --}}
My Reservations
{{-- </div> --}}
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
The result I'm getting is that the button does toggle but the toggle button of all the user come red after on refresh page or when the page loads.
try
buttonStatus() {
return(this.status==0) ? 'btn btn-outline-danger text-danger' : 'btn btn-success ';
}

laravel 5.4/ vue js dont iterate my array

Hello I want to make a loop to iterate an array of data retrieve from a controller but I have an error message in vue js I can not find where is my error help me please I start with a vue js
here is my code
controller.php
public function index(){
$post= Posts::with('likes','comments', 'user')->orderBy('created_at','DESC')->get();
return $post ;
}
vue.js
const root = new Vue({
el: '#root',
data: {
msg: 'Update New Post:',
content: '',
posts: []
},
ready: function ready() {
this.created();
},
created: function created() {
var _this = this;
axios.get('http://localhost:8000/mur/posts')
.then(response => {
_this.posts = response.data;
//we are putting data into our posts array
console.log(response.data);
// show if success
Vue.filter('myOwnTime', function(value){
return moment(value).fromNow();
});
})
.catch(function (error) {
console.log(error); // run if we have error
});
}
},
view
<div v-for="post, key in posts">
<div class="col-md-12 col-sm-12 col-xs-12 all_posts">
<div class="col-md-1 pull-left">
<img :src="'{{asset('storage/avatar')}}/' + post.avatar"
style="width:50px;">
</div>
<div class="col-md-10" style="margin-left:10px">
<div class="row">
<div class="col-md-11">
<p><a :href="'{{url('profile')}}/' + post.slug" class="user_name"> #{{post.user.name}}</a> <br>
<span style="color:#AAADB3"> #{{ post.created_at }}
<i class="fa fa-globe"></i></span></p>
</div>
<div class="col-md-1 pull-right">
#if(Auth::check())
<!-- delete button goes here -->
<a href="#" data-toggle="dropdown" aria-haspopup="true">
{{--<img src="{{Config::get('app.url')}}/public/img/settings.png" width="20">--}}
</a>
<div class="dropdown-menu">
<li><a>some action here</a></li>
<li><a>some more action</a></li>
<div class="dropdown-divider"></div>
<li v-if="post.user_id == '{{Auth::user()->id}}'">
<a #click="deletePost(post.id)">
<i class="fa fa-trash"></i> Delete </a>
</li>
</div>
#endif
</div>
</div>
</div>
<p class="col-md-12" style="color:#000; margin-top:15px; font-family:inherit" >
#{{post.content}}
</p>
<div style="padding:10px; border-top:1px solid #ddd" class="col-md-12">
<!-- like button goes here -->
#if(Auth::check())
<div v-for="">
<div v-if="">
<p class="likeBtn" #click="likePost(post.id)">
<i class="fa fa-heart-o"></i>
</p>
</div>
</div>
data : #{{ post.likes.length }}
#endif
</div>
</div>
</div>
web.php
Route::get('mur/posts', 'PostController#index');
posts [ ] return this
[{"id":8,
"user_id":3,
"content":"content 1",
"status":0,
"created_at":"2017-12-27 22:43:20",
"updated_at":"2017-12-27 22:43:20",
"likes":[{"id":2,"posts_id":7,"user_id":3,"created_at":"2017-12-27 16:38:33","updated_at":null}],
"comments":[],
"user":{
"id":3,"name":"toto","sulg":"toto","email":"toto#hotmail.fr","avatar":"215563.jpg","is_actif":"activ\u00e9","created_at":"2017-12-06 15:30:42","updated_at":"2017-12-06 17:04:41"}
},
{"id":7,
"user_id":9,
"content":"coucou",
"status":0,
"created_at":"2017-12-27 16:07:01",
"updated_at":"2017-12-27 16:07:01",
"likes":[{"id":2,"posts_id":7,"user_id":4,"created_at":"2017-12-27 16:38:33","updated_at":null}],
"comments":[],
"user":{"id":9,"name":"blop","sulg":"blop","email":"blop#gmail.com","avatar":"logoBee.png","is_actif":"activ\u00e9","created_at":"2017-12-17 14:37:29","updated_at":"2017-12-17 14:37:29"}}
error in console

Resources