I'm currently developing a comment function in Laravel 5. I want to display instantly the comment the user just post. So how can I achieve that? I have tried to use load() method in AJAX, but it still doesn't work.
Here is the controller to insert a comment:
public function newComment(Request $request)
{
try {
$date_format = date('Y-m-d');
$comment=new Comment();
$comment->user_id=Auth::user()->id;
$comment->introduce=$request->introduce;
$comment->completed_day=$request->completed_day;
$comment->allowance=str_replace( ',', '', $request->allowance);
$comment->post_at=$date_format;
$comment->job_id=$request->job_id;
$comment->save();
return response()->json(array('mess'=>'Success'));
}
catch (Exception $ex) {
return response()->json(array('err'=>'Error'));
}
}
Here is the view and {{$jobReply -> user -> full_name }} im using ORM to get user name
<div class="panel-body" id="job_comment_post" style="text-align:left">
<table class="table table-hover">
<thead>
<tr>
<th>Freelancer name</th>
<th>Introduce</th>
<th>Completed day</th>
<th>Allowance</th>
</tr>
</thead>
<tbody>
#foreach($job_comment as $jobReply)
<tr>
<td>{{$jobReply -> user -> full_name }}</td>
<td>{{$jobReply -> introduce}}</td>
<td>{{$jobReply -> completed_day}}</td>
<td>{{number_format($jobReply -> allowance)}}</td>
</tr>
#endforeach()
</tbody>
</table>
<div class="details_pagi">
{!! $job_comment->render() !!}
</div>
</div>
This is AJAX to insert comment:
$(document).ready(function() {
$('#btnInsertComment').click(function(event) {
event.preventDefault();
var data=$("#commentForm").serialize();
$.ajax({
url: '/postComment',
type: 'POST',
data: data,
success:function(data) {
alert(data.mess);
//job_comment_post is the div i want to load new comment
$("#job_comment_post").load();
$("#commentForm")[0].reset();
},
error:function(data) {
alert(data.err);
}
});
});
});
Related
I have two tables Session (parent) and Period (child) with a one to many relationship. I'm now trying to display all sessions with periods.
It works fine but my data is only displayed in console and not in Vue.
public function allWithPeriods()
{
$sessions = Session::orderBy('end_date', 'desc')
->with('_periods')
->get();
return response()->json(['sessions' => $sessions]);
}
Session Model
public function periods()
{
return $this->hasMany('App\Period')->with(["course_plans"]);
}
public function _periods()
{
return $this->hasMany('App\Period');
}
Period Model
class Period extends Model
{
public function session()
{
return $this->belongsTo('App\Session');
}
}
Blade
<template>
<div class="container">
<h2 class="text-center p-2 text-white bg-primary mt-5">La liste des Sessions Universitaires</h2>
<v-simple-table>
<template v-slot:default>
<thead>
<tr>
<th class="text-left">#</th>
<th class="text-left">Titre de la session</th>
<th class="text-left">Type</th>
<th class="text-left">Date de début de session</th>
<th class="text-left">Date de cloture de session</th>
<th class="text-left">Actions</th>
</tr>
</thead>
<tbody v-for="session in sessions.data" :key="session.id">
<tr>
<td>
<p class="font-weight-medium">{{session.id}}</p>
</td>
<td>
<p class="font-weight-medium">{{session.name}}</p>
</td>
<td>
<p class="font-weight-medium">{{session.type }}</p>
</td>
<td>
<p class="font-weight-medium">{{session.start_date}}</p>
</td>
<td>
<p class="font-weight-medium">{{session.end_date}}</p>
</td>
<td>
<v-btn color="success" fab x-small dark :to="{ name:'/get_session', params:{ id: session.id } }">
<v-icon>mdi-pencil</v-icon>
</v-btn>
<v-btn color="red" fab x-small dark #click.prevent="deleteSession(session.id)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</td>
</tr>
</tbody>
</template>
</v-simple-table>
<pagination :data="sessions" #pagination-change-page="getResults"></pagination>
<v-btn
depressed
color="success"
to="/add_session"
>
<v-icon left>mdi-plus</v-icon>
Ajouter
</v-btn>
</div>
</template>
<script>
export default {
name:'sessions',
data() {
return {
url: document.head.querySelector('meta[name="url"]').content,
sessions: {},
}
},
created() {
this.loadData();
},
mounted() {
console.log('session component mounted ');
},
methods: {
loadData() {
let url = this.url + '/api/session/get';
axios.get(url)
.then(response => {
this.sessions = response.data;
console.log(this.sessions);
}).catch(error => {
console.log(error)
});
},
getResults(page = 1) {
axios.get('http://localhost:8000/api/session/get?page=' + page)
.then(response => {
this.sessions = response.data;
});
},
deleteSession(id) {
let url = this.url + `/api/session/delete_session/${id}`;
this.axios.delete(url)
.then(response => {
if (response.status) {
this.$utils.showSuccess('success', response.message);
this.loadData();
} else {
this.$utils.showError('Error', response.message);
}
});
}
},
}
</script>
First of all, you should define your sessions data as an array, not as an object. Otherwise, you could face some reactivity issues.
So instead of this:
data() {
return {
url: document.head.querySelector('meta[name="url"]').content,
sessions:{}
}
},
you should declare your sessions as:
data() {
return {
url: document.head.querySelector('meta[name="url"]').content,
sessions:[]
}
},
On the other hand, you are iterating over sessions.data instead of sessions. If you take a look at your developer console you will probably notice that there is no .data within sessions.
Saying that you should iterate in this way
<tbody v-for="session in sessions" :key="session.id">
...
</tbody>
I am working on old laravel project and I have to modify existing one. So I am now trying to understand the code. The project is on laravel and yajra datatable. I can't understand how the destroy function work ? In the view there is a no call for destroy function but when I click the delete button still it is working.
Controller
public function loadSizes()
{
$sizes = Size::select(['id', 'name', 'code'])->get();
return DataTables::of($sizes)
->addColumn('action', function ($size) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $size->id . '" class="btn btn-default remove-size remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
public function destory(Request $request)
{
$result = Size::where('id', $request->input('size_id'))->delete();
if ($result) {
return "SUCCESS";
} else {
return "FAIL";
}
}
view
#extends('layouts.sidebar')
#section('content')
<div class="row">
<div class="col-sm-12 pad-main">
<div class="row">
<div class="col-md-6">
<h4 class="cat-name"> Size List</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 table-responsive pad-tbl">
<table class="table table-striped" id="size_table">
<thead>
<tr>
<th scope="col"> Name</th>
<th scope="col"> Code</th>
<th scope="col"> Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#if (Session::has('action'))
#if (Session::get('action') == "create")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size creation successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size creation fail");</script >
#endif
#elseif(Session::get('action') == "update")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size update successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size update fail");</script >
#endif
#endif
#endif
<script>
$(document).ready(function () {
$('#size_table').DataTable({
language: {
searchPlaceholder: "Search records"
},
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
processing: true,
serverSide: true,
ajax: '{!! url(' / load - sizes') !!}',
columns: [
{data: 'name', name: 'name'},
{data: 'code', name: 'code'},
{data: 'action', name: 'action'},
]
});
});
$(document.body).on("click", ".remove-size", function () {
var size_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Size ?", "deleteSize(" + size_id + ")");
});
function deleteSize(id) {
$.ajax({
type: 'get',
url: '{!! url('delete-size') !!}',
data: {size_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS", "Delete Size successful");
}
}, error: function (data) {
showAlert("FAIL", "Delete Size fail");
}
});
}
</script>
#endsection
At the bottom of the blade view there is an AJAX in function destory(id).
That AJAX is sending a GET request to a URL delete-size with size id.
Now, if you search your web.php file for that URL (location - routes/web.php), you'll find something like this:
Route::get('delete-size', 'SizeController#destory');
This route would be sending the size id to your destory function, which is in turn searching the Size in your DB and deleting it.
// Controller
public function destroy($id)
{
Tag::find($id)->delete();
Toastr::success('Tag Successfully Deleted',"Success");
return redirect()->back();
}
// Route
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::resource('tag','TagController');
});
// HTML file
<form id="delete-form-{{ $tag->id }}" action="{{ route('admin.tag.destroy',$tag->id) }}" method="POST" style="display: none;">
#csrf
#method('DELETE')
</form>
I am new in the web programming subject. I am doing a project using laravel and Blade for the views, and I want to create an X-editable table for one of my databases so the user doesn't need to enter to a different view to edit the data.
Anyway, I am having a lot of trubbles.
I have this database in mysql:
MySql database
Route
I am doing this in the web.php file that is in the file routes
Route::resource('/test','PruebaController');
Route::get('/test', 'PruebaController#index')->name('test');
Route::post('test/updatetest','PruebaController#updatetest')->name('updatetest');
Controller
public function index(Request $request)
{
if ($request){
$test=DB::table('pruebas')
->orderBy('nombre','asc')
->get();
$test_model = new Prueba();
$fillable_columns = $test_model->getFillable();
foreach ($fillable_columns as $key => $value)
{
$test_columns[$value] = $value;
}
return view('test.index')
->with('test', $test)
->with('test_columns', $test_columns);
}
}
public function updatetest(Request $request, $id)
{
try
{
$id =$request->input('pk');
$field = $request->input('name');
$value =$request->input('value');
$test = Prueba::findOrFail($id);
$test->{$field} = $value;
$test->save();
}
catch (Exception $e)
{
return response($e->intl_get_error_message(), 400);
}
return response('',200);
}
View
#extends ('layouts.admin')
#section ('contenido')
<div class="panel-heading">
<h4>
Listado de nombres
</h4>
#if (count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</div>
<div class="panel-body">
<form action="{{route('updatetest')}}" method="post">
{{csrf_field()}}
<table class="table table-hover nowrap" id="example" width="100%">
<thead class="thead-default">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Cédula</th>
<th>Edad</th>
</tr>
</thead>
#foreach ($test as $t)
<tbody>
<tr>
<td>{{$t->id}}</td>
<td>
<a
href="#"
class="nombre"
data-type="text"
data-pk="{{$t->id}}"
data-value="{{$t->nombre}}"
data-title="Cambie el nombre"
data-url="{{route('updatetest') }}">
{{$t->nombre}}
</a>
</td>
<td>
<a
href="#"
class="cedula"
data-type="number"
data-pk="{{$t->id}}"
data-value="{{$t->cedula}}"
data-title="Cambie la cedula"
data-url="{{route('updatetest') }}">
{{$t->cedula}}
</a>
</td>
<td>
<a
href="#"
class="edad"
data-type="number"
data-pk="{{$t->id}}"
data-value="{{$t->edad}}"
data-title="Cambie la edad"
data-url="{{route('updatetest') }}">
{{$t->edad}}
</a>
</td>
</tr>
</tbody>
#endforeach
</table>
</form>
</div>
#endsection
AJAX script
<script type="text/javascript">
$(document).ready(function() {
//toggle `popup` / `inline` mode
$.fn.editable.defaults.mode = 'inline';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
id = $(this).data('pk');
url = $(this).data('url');
//make username editable
$('.nombre').editable({
url: url,
pk: id,
type:"text",
validate:function(value){
if($.trim(value) === '')
{
return 'This field is required';
}
}
});
$('.cedula').editable({
url: url,
pk: id,
type:"number",
validate:function(value){
if($.trim(value) === '')
{
return 'This field is required';
}
}
});
$('.edad').editable({
url: url,
pk: id,
type:"number",
validate:function(value){
if($.trim(value) === '')
{
return 'This field is required';
}
}
});
});
</script>
The problem is that the x-editable is not working, when I click on the field nothing happens. Any idea why is that?
I would really appreciate your help.
Change
<form action="{{route('test/updatetest')}}" method="post">
To
<form action="{{route('updatetest')}}" method="post">
The route function generates a URL for the given named route:
$url = route('routeName');
You can read more about it here
My problem, I don't know how to set $model->code_reg when I use Ajax post. I want save my model code_reg for looping for my ajax post. But its my controller create not work save it
This is my form:
<div class="form-group">
<?= $form->field($model, 'code_reg')->textInput(['readonly' => true]) ?>
</div> <!--I'm using random code and It's was display for this-->
<table id="sampleTbl", class="table table-striped table-bordered">
<thead>
<th>Name</th>
<th>Age</th>
</thead><tbody>
<tr>
<td>William</td>
<td>29</td>
</tr><tr>
<td>Nency</td>
<td>25</td>
</tr>
</tbody>
</table>
<div class="form-group">
<?= Html::submitButton('Create',['class' => 'btn btn-success', 'id' => 'idOfButton']) ?>
</div>
This is my jQuery function:
$('#idOfButton').click(function(){
var TableData = new Array();
$('#sampleTbl tr').each(function(row, tr){
TableData[row]={
'name' : $(tr).find('td:eq(0)').text(),
'age' : $(tr).find('td:eq(1)').text()
}
});
TableData.shift(); // first row will be empty - so remove
var jsonEncode = JSON.stringify(TableData);
// alert(jsonEncode);
$.ajax({
type: "POST",
data: "pTableData=" + jsonEncode,
success: function(msg){
// alert(msg);
},
});
});
This is my controller actionCreate():
$model = new Mutiplearray();
if(Yii::$app->request->isAjax) {
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData, true);
foreach ($tableData as $key) {
$model->isNewRecord = true;
$model->id = NULL;
$model->name = $key['name'];
$model->age = $key['age'];
$model->code_reg = $model->code_reg; // <---This is my problem I can't save it `code_reg` for ajax looping
$model->save();
}
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
I got not set for code_reg when I use like this. How to save model when I use ajax too?
So i create a search engine in my laravel application, the only problem i have is displaying it on the same page,
this is what i have in my views
<div class="search">
{{Form::open(array('url' => 'admin/search', 'method' => 'post'))}}
{{Form::text('keyword',null,array(
'class' => 'form-control',
'placeholder' => 'Enter keyword...'
))}}<br>
{{Form::submit()}}
</div>
<br>
<div class="searchs">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<th>Title</th>
<th>Date Created</th>
<th>Actions</th>
</thead>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
and in my controller
public function search_keyword()
{
$input = Input::get('keyword');
$result = Post::where('title','LIKE','%' .$input. '%')->get();
return Redirect::route('index')
->with('result',$result);
}
but i was hoping that i could do this in ajax request but I don't know jquery or even js.. help
You have to catch the submit of the form with Javascript (vanilla or e.g. jquery), find the value the user is searching for and start an ajax request. (jQuery $.get() or native XMLHttpRequest())
Now you need to make sure that laravel accepts the ajax request properly and return the request as JSON.
If your request successfully returns data, use the success function of the ajax request to process the data. During the search, you could show some loading icon to notify the user that the search process is running.
To start with, add an id to the form and use jquery to listen for the submit event.
<script type="text/javascript">
$('#my-form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "/api/search",
type: 'POST',
data: {
value: $("input:first").val()
},
dataType: 'json',
success: function (response) {
console.log(response);
}
});
});
</script>
Next, register a route for the /api/search request and return your search request with return response()->json(['result' => $result]); (laravel 5)
If everything is right, you should see the result in the console of your browser.