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?
Related
So when I put a route name with a single parameter it works flawlessly but when I pass named route with two parameters I get a 500 error in my console which looks like this:GET http://127.0.0.1:8000/admin/packages/package-programs/kathmandu/action?query= 500 (Internal Server Error).
<?php
namespace App\Http\Controllers\AdminVisible;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Program;
use App\Package;
use DB;
class PackageProgramController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index($packageSlug)
{
$showCounts = Program::count();
$packages = Package::firstOrFail();
return view('admin.pages.packageprogram',compact('showCounts','packageSlug','packages'));
}
function action($packageSlug,Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('programs')
->where('id', 'like', '%'.$query.'%')
->orWhere('day', 'like', '%'.$query.'%')
->orWhere('Package_Type', 'like', '%'.$query.'%')
->orWhere('title', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->get();
}
else
{
$data = DB::table('programs')
->orderBy('id', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$packageProgram = ['packageProgram' => $row->id];
$route = route('PackageProgram.edit',['packageSlug' => $packageSlug, 'packageProgram' => $packageProgram]);
$output .= '
<tr>
<th scope="row"><input type="checkbox" name="ids[]" class="selectbox" value="'.$row->id.'" onchange="change()"></th>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->id.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->day.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->title.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->description.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="12">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
public function create($packageSlug, Package $package)
{
return view('admin.create.createPackageProgram',compact('packageSlug','package'));
}
public function store($packageSlug,Request $request)
{
$packages = Package::where('slug', $packageSlug)->firstOrFail();
$data = request()->validate([
'day' => 'required',
'title' => 'required',
'description' => 'required',
]);
$packages->program()->create($data);
switch ($request->input('action')) {
case 'preview':
return redirect()->intended(route('PackageProgram',$packageSlug))->with('message', 'Package Program has been added.');
break;
default:
return redirect()->back()->with('message', 'Package Program has been added.');
break;
}
}
public function edit($packageSlug,Program $packageProgram,Package $package)
{
return view('admin.edit.editPackageProgram',compact('packageSlug','packageProgram','package'));
}
public function update($packageSlug, Program $packageProgram)
{
$data = request()->validate([
'day' => 'required',
'title' => 'required',
'description' => 'required',
]);
$packageProgram->update($data);
return redirect()->intended(route('PackageProgram',$packageSlug))->with('message', 'Package Program has been updated.');
}
public function delete(Request $request) {
$data = request()->validate([
'deleteSelected' => 'required',
]);
$id = $request->get('ids');
$data = DB::delete('delete from programs where id in ('.implode(",",$id).')');
return redirect()->back()->with('message', 'Testimony has been deleted.');
}
}
My blade file looks something like this:
#extends('layouts.app')
#section('style')
<link href="{{ asset('css/Admin/sql-data-viewer.css') }}" rel="stylesheet">
<style></style>
#endsection
#section('content')
<section class="data-viewer">
<div class="d-flex justify-content-between px-3">
<h3 class="text-white">Select {{$package->Package_Name}} {{$package->Package_Type}} Days to change</h3>
<button type="button" class="btn add-data text-white rounded-pill">Add Day <i class="fas fa-plus"></i></button>
</div>
<form>
#csrf
#method('DELETE')
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
<div class="d-flex justify-content-between selectDelete">
<div class="delete pl-3 mt-3 mb-3">
<label for="deleteSelected">Action:</label>
<select name="deleteSelected" id="deleteSelected" class="#error('deleteSelected') is-invalid #enderror" name="deleteSelected" >
<option disabled selected>---------</option>
<option>Delete Selected Package Program</option>
</select>
<button formaction="{{ route('PackageProgram.delete',$package) }}" formmethod="POST" type="submit" class="go" id="deleleGo" onclick="deleteBtn()">Go</button>
<span id="selected">0</span> of {{$showCounts}} selected
#error('deleteSelected')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<strong id="selectError">You must check at least one checkbox</strong>
</div>
<div class="search pr-3 mt-3 mb-3">
<label for="search">Search:</label>
<input id="search" type="text" color="#000" class="rounded #error('search') is-invalid #enderror" name="search" value="{{ old('search') }}" autocomplete="search" placeholder="Search">
#error('search')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<table class="table table-hover table-striped table-dark">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</form>
</section>
#endsection
#section('script')
<script src="{{ asset('/js/sqlData.js') }}"></script>
<script>
$(document).ready(function(){
fetch_data();
function fetch_data(query = '')
{
$.ajax({
url:"{{ route('PackageProgram.action',$packageSlug) }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_data(query);
});
});
function checkboxError(){
var number = document.querySelectorAll('.selectbox:checked').length;
if(number == 0) {
var a = document.getElementById("selectError").style.display = "block";
return false;
}
}
window.addEventListener('DOMContentLoaded', (event) => {
var deleteBtn = document.getElementById("deleleGo");
deleteBtn.onclick = checkboxError;
});
</script>
#endsection
So my route file looks something like this:
Route::prefix('package-programs')->group(function() {
Route::get('/', 'AdminVisible\packagePackageProgramController#index')->name('PackagePrograms');
Route::get('/action', 'AdminVisible\packagePackageProgramController#action')->name('PackagePrograms.action');
Route::prefix('{packageSlug}')->group(function() {
Route::get('/', 'AdminVisible\PackageProgramController#index')->name('PackageProgram');
Route::get('/action', 'AdminVisible\PackageProgramController#action')->name('PackageProgram.action');
Route::get('/create', 'AdminVisible\PackageProgramController#create')->name('PackageProgram.create');
Route::post('/create', 'AdminVisible\PackageProgramController#store')->name('PackageProgram.store');
Route::delete('/delete','AdminVisible\PackageProgramController#delete')->name('PackageProgram.delete');
Route::get('/{packageProgram}/edit', 'AdminVisible\PackageProgramController#edit')->name('PackageProgram.edit');
Route::patch('/{packageProgram}', 'AdminVisible\PackageProgramController#update')->name('PackageProgram.update');
});
});
It might be I do not know how to pass named route with two parameters but in my blade file, I been doing it like this, and there it works. Is it something different that must be done in the controller.
First start from blade (please check comments):
#extends('layout')
#section('content')
<div class="row">
<table class="table table-hover table-striped table-dark" id="slugTb">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: "{{ route('test.action') }}",
method: 'GET',
data: {
'slug': '{{ $packageSlug }}',
'query': query
},
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
#endsection
You used deprecated jquery method like success check
Better use this three: done,fail,always
Next route web.php:
Route::get('action', ['as' => 'test.action', 'uses' => 'TestController#action']);
In your case better to use Request params bag so that you can add as much params as you want.
Next controller:
function action(Request $request)
{
$total_row = 1;
$packageSlug = $request->get('slug'); //names that you set in ajax data tag: {'slug': '{{ $packageSlug }}','query': query}
$query = $request->get('query');
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
}
You should return something from the controller so blade can show that data and json encode it so that js could parse it. That is why return response()->json($data);
Other way:
route:
Route::get('/action/{slug}/{query}',['as' => 'test.action', 'uses' => 'TestController#action']);
blade script:
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: 'action/{{ $packageSlug }}/' + query,
method: 'GET',
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
and controller:
function action($slug, $query)
{
$total_row = 1;
$packageSlug = $slug;
$query = $query;
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
}
Not recommended just because you manually type route in ajax request: url: 'action/{{ $packageSlug }}/' + query if your route changes you have to change it in js.
I just followed a YouTube tutorial where the tutor did something similar to what i wanted
Tutorial Link : Laravel 5.8 - Custom Search in Datatables using Ajax
And in the tutorial the tutor uses Datatable to load all the data and also to show all the filtered results.
I need to have my own custom desigh where i can add a #foreach and customize the design,
i don't know how can i do it i tried many way and i failed.
Can someone suggest me a solution for it or suggest me any tutorials to be followed where i can make the filtered data load into my view as i wanted.
Here's my stores.blade.php where the search fields and the table is,
<h3 align="center">Store Locator</h3>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="form-group">
<select name="filter_district" id="filter_district" class="form-control" required>
<option value="">Select Distric</option>
#foreach ($district_name as $district)
<option value="{{ $district->district }}">{{ $district->district }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<select name="filter_outlet" id="filter_outlet" class="form-control" required>
<option value="">Select Outlet</option>
#foreach($outlet_name as $country)
<option value="{{ $country->outlet }}">{{ $country->outlet }}</option>
#endforeach
</select>
</div>
<div class="form-group" align="center">
<button type="button" name="filter" id="filter" class="btn form-submit">Filter</button>
<button type="button" name="reset" id="reset" class="btn form-submit">Reset</button>
</div>
</div>
<div class="col-md-4"></div>
</div>
<br />
<div class="table-responsive">
<table id="store_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Outlet</th>
<th>Province</th>
<th>District</th>
<th>Number 1</th>
<th>Number 2</th>
<th>Number 3</th>
<th>Address</th>
</tr>
</thead>
</table>
</div>
Here's the Script in the stores.blade.php
<script>
$(document).ready(function(){
fill_datatable();
function fill_datatable(filter_district = '', filter_outlet = '')
{
var dataTable = $('#store_data').DataTable({
processing: true,
serverSide: true,
ajax:{
url: "{{ route('store-locatorr.index') }}",
data:{filter_district:filter_district, filter_outlet:filter_outlet}
},
columns: [
{
data:'id',
name:'id'
},
{
data:'outlet',
name:'outlet'
},
{
data:'province',
name:'province'
},
{
data:'district',
name:'district'
},
{
data:'no1',
"render": function(data, type, row, meta) {
if (type === 'display') {
data = '<a class="gray" href="tel:' + data + '">' + data + '</a>';
}
return data;
},
name:'no1'
},
{
data:'no2',
"render": function(data, type, row, meta) {
if (type === 'display') {
data = '<a class="gray" href="tel:' + data + '">' + data + '</a>';
}
return data;
},
name:'no2'
},
{
data:'no3',
"render": function(data, type, row, meta) {
if (type === 'display') {
data = '<a class="gray" href="tel:' + data + '">' + data + '</a>';
}
return data;
},
name:'no3'
},
{
data:'address',
name:'address'
}
]
});
}
// $('#filter_outlet').on('change',function(){
$('#filter').click(function(){
var filter_district = $('#filter_district').val();
var filter_outlet = $('#filter_outlet').val();
if(filter_district != '' && filter_district != '')
{
$('#store_data').DataTable().destroy();
fill_datatable(filter_district, filter_outlet);
}
else
{
alert('Select Both filter option');
}
});
$('#reset').click(function(){
$('#filter_district').val('');
$('#filter_outlet').val('');
$('#store_data').DataTable().destroy();
fill_datatable();
});
});
</script>
Here's my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
protected $table = 'stores';
}
Here's my StoreLocatorController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Store;
class StoreLocatorController extends Controller
{
function index(Request $request)
{
if(request()->ajax())
{
if(!empty($request->filter_district))
{
$data = Store::select('id','outlet', 'province', 'district', 'no1', 'no2', 'no3', 'address')
->where('district', $request->filter_district)
->where('outlet', $request->filter_outlet)
->get();
}
else
{
$data = Store::select('id','outlet', 'province', 'district', 'no1', 'no2', 'no3', 'address')
->get();
}
return datatables()->of($data)->make(true);
}
$outlet_name = Store::select('outlet')
->groupBy('outlet')
->orderBy('outlet', 'ASC')
->get();
$district_name = Store::select('district')
->groupBy('district')
->orderBy('district', 'ASC')
->get();
return view('test.stores', compact('outlet_name','district_name'));
// $count = Store::orderBy('id')->where('district','Kandy')->count();
// $store = Store::orderBy('id','asc')->get();
// return view("test.stores")->with('store',$store)->with('count',$count);
// return view("test.stores");
}
}
Here's my web routes
Route::resource('/store-locatorr', 'StoreLocatorController');
This is my database
This is how my ui looks like
I just wanted to know a way how can i display the results which loaded in the table from database to be loaded into a foreach so that i can design the way i wanted, while the search functionality works as it is,
Can someone help me out or please suggest me something where i can clear this issue,
You need to include the district name of the store when you send the result by eager load. So in your store model, create a belongsTo relationship
public function district() {
return $this->belongsTo('App\District', 'district');
}
So when you send your result, you can write
$data = Store::select('id','outlet', 'province', 'district', 'no1', 'no2', 'no3', 'address')
->where('district', $request->filter_district)
->where('outlet', $request->filter_outlet)
->with(['district'])
->get();
I am using Laravel 5. In this application, the staff name can be added and deleted dynamically. For creating new records, all functions run smoothly. However, I have some difficulties in updating the records. In 'edit' page, the staff names created are displayed and can be changed. These names can be updated. But, I put add button and delete button to enable user to add new staff name or delete existing staff name.
My function just can update existing record in database. But the new added staff name not inserted in database. This is my function to update in controller.
public function update(Request $request, $id)
{
$demo = Demo::findOrFail($id);
$demo->tajuk_demo = $request->tajuk_demo;
$demo->syarikat_id = $request->nama_syarikat;
$demo->peralatan_sistem = $request->peralatan_sistem;
$demo->tarikhmasa = $request->tarikhmasa;
$demo->tarikhmasa_tamat = $request->tarikhmasa_tamat;
$demo->tempat_demo = $request->tempat_demo;
$demo->ulasan_demo = $request->ulasan_demo;
$demo->komen_demo = $request->komen_demo;
$demo->update();
$pegawai = $request->all();
// $rekod_id = $pegawai['rekod_id'];
$itemRegistrationID = $pegawai['nama'];
$OperasiID = $pegawai['pangkat'];
$SectionID = $pegawai['bahagian'];
$pegawai_semasa = Pegawai::where('rekod_id', '=', Input::get('rekod_id'))->exists();
$peg_hadir = Pegawai::where('demo_id', '=', $id)
->get();
// Update the existing record
foreach($peg_hadir as $peg){
$key = array_search($peg->rekod_id, $pegawai['rekod_id']);
$peg->itemRegistrationID = $itemRegistrationID[$key];
$peg->OperasiID = $OperasiID[$key];
$peg->SectionID = $SectionID[$key];
$peg->save();
}
if (is_null($pegawai_semasa))
{
// Insert new record into database
$count = count(Input::get('nama'));
// get data
$itemRegistrationID = Input::get('nama');
$OperasiID = Input::get('pangkat');
$SectionID = Input::get('bahagian');
//loop through and save data
for($i = 0; $i < $count; ++$i) {
$pegawai = new Pegawai;
$pegawai->demo_id = $id;
$pegawai->itemRegistrationID = $itemRegistrationID[$i];
$pegawai->OperasiID = $OperasiID[$i];
$pegawai->SectionID = $SectionID[$i];
$pegawai->save();
}
}
else
{
return redirect('demo');
}
}
This is the code in view blade for edit page:
<div class="form-group">
<div class="row">
<input type="button" class="add-row" value="Add">
<button type="button" class="delete-row">Delete</button>
</div>
</div>
<!--mula table -->
<div class="form-group">
<div class="row">
<div class="col-lg-10">
<table class="table table-striped table-bordered" id="pegawaihadir_table" >
<thead>
<tr>
<td class="text-center col-lg-1"><strong>Pilih</strong></td>
<td class="text-center col-lg-1"><strong>Pangkat</strong></td>
<td class="text-center col-lg-3"><strong>Nama</strong></td>
<td class="text-center col-lg-2"><strong>No Badan</strong></td>
<td class="text-center col-lg-2"><strong>Seksyen</strong></td>
<td class="text-center col-lg-2"><strong>No Tel</strong></td>
<td class="text-center col-lg-2"><strong>Ext</strong></td>
</tr>
</thead>
<tbody>
#foreach($PegawaiHadir as $value)
<tr>
<td><input type="checkbox" name="rekod" style="width:20px">
{!! Form::hidden('rekod_id[]', $value['rekod_id'], ['class' => 'form-control']) !!}
</td>
<td class="text-center">{{ Form::text('pangkat[]', $value['OperasiID'], ['class' => 'form-control pangkat', 'readonly' => 'true']) }}</td>
<td>
{{ Form::select('nama[]', $pegawai, $value['itemRegistrationID'], ['class' => 'form-control nama', 'required' => '']) }}
</td>
<td class="text-center">{{ Form::text('no[]', $value['Nobadan'], ['class' => 'form-control no', 'readonly' => 'true']) }}</td>
<td class="text-center">{{ Form::text('bahagian[]', $value['SectionID'], ['class' => 'form-control bahagian', 'readonly' => 'true']) }}</td>
<td class="text-center">{{ Form::text('telefon[]', $value['notelttp'], ['class' => 'form-control telefon', 'readonly' => 'true']) }}</td>
<td class="text-center">{{ Form::text('ext[]', $value['ext'], ['class' => 'form-control ext', 'readonly' => 'true']) }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
For dynamic fields, I am using js code to add and delete the record displayed in the page.
<script>
count=1;
$(document).ready(function(){
$(".add-row").click(function(){
var markup = '<tr><td><input type="checkbox" name="rekod" style="width:20px"></td>';
markup += '<td><input type="text" class="form-control pangkat" name="pangkat[]" style="width:100px" readonly></td>';
markup += '<td><select class="form-control select2 nama" name="nama[]" style="width:300px"><option value="">Pilih</option><?php foreach($pegawai as $key => $value):echo '<option value="'.$key.'">'.addslashes($value).'</option>'; endforeach; ?></select></td>';
markup += '<td><input type="text" class="form-control no" name="no[]" style="width:100px" readonly></td>';
markup += '<td><input type="text" class="form-control bahagian" name="bahagian[]" style="width:100px" readonly></td>';
markup += '<td><input type="text" class="form-control telefon" name="telefon[]" style="width:100px" readonly></td>';
markup += '<td><input type="text" class="form-control ext" name="ext[]" style="width:100px" readonly></td></tr>';
$("table tbody").append(markup);
count++;
});
$(document).on('change', 'select.form-control.nama', function() {
var PegID = jQuery(this).val();
var row = $(this);
// alert(PegID);
if(PegID)
{
jQuery.ajax({
context: this,
url : 'get_pegawai/'+PegID,
type : "GET",
dataType : "json",
success:function(data)
{
console.log(data);
$(this).closest('tr').find('td .form-control.pangkat').val(data.operasiname);
$(this).closest('tr').find('td .form-control.no').val(data.Nobadan);
$(this).closest('tr').find('td .form-control.bahagian').val(data.sectionname);
$(this).closest('tr').find('td .form-control.telefon').val(data.notelttp);
$(this).closest('tr').find('td .form-control.ext').val(data.ext);
}
});
}
else
{
$(this).closest('tr').find('td .form-control.pangkat').empty();
$(this).closest('tr').find('td .form-control.no').empty();
$(this).closest('tr').find('td .form-control.bahagian').empty();
$(this).closest('tr').find('td .form-control.telefon').empty();
$(this).closest('tr').find('td .form-control.ext').empty();
}
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="rekod"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
</script>
I also doesn't know how to identify the selected staff name to be deleted from existing record in database. I am providing a complete code to ease anyone who want to help to understand better. Thank you.
Make this ajax call into an IIFE
$(function(){
$(document).on('change', 'select.form-control.nama', function() {
var PegID = jQuery(this).val();
var row = $(this);
// alert(PegID);
if(PegID)
{
jQuery.ajax({
context: this,
url : 'get_pegawai/'+PegID,
type : "GET",
dataType : "json",
success:function(data)
{
console.log(data);
$(this).closest('tr').find('td .form-control.pangkat').val(data.operasiname);
$(this).closest('tr').find('td .form-control.no').val(data.Nobadan);
$(this).closest('tr').find('td .form-control.bahagian').val(data.sectionname);
$(this).closest('tr').find('td .form-control.telefon').val(data.notelttp);
$(this).closest('tr').find('td .form-control.ext').val(data.ext);
}
});
}
else
{
$(this).closest('tr').find('td .form-control.pangkat').empty();
$(this).closest('tr').find('td .form-control.no').empty();
$(this).closest('tr').find('td .form-control.bahagian').empty();
$(this).closest('tr').find('td .form-control.telefon').empty();
$(this).closest('tr').find('td .form-control.ext').empty();
}
});
});
And also change update() method to save() method in your controller.
I have a Symfony app which allows CRUD operations on some events and also searching for them. The problem I get is when trying to get the results I'm searching for displayed without refreshing the page. It's the first time I'm using ajax and I think it's something wrong with the function. When I search for a word in any event name, the page is not refreshing and it shows undefined instead of showing the entries.
I appreciate any help!
Here's the method from the Controller:
public function ajaxListAction(Request $request){
//fetch the data from the database and pass it to the view
$em = $this->getDoctrine()->getManager();
$searchTerm = $request->get('search');
$form = $this->createFormBuilder()
->add('search', SubmitType::class, array('label' => 'Search', 'attr' => array('class' => 'btn btn-primary', 'style' => 'margin-bottom:15px')))->getForm();
$organizer = array();
if($searchTerm == ''){
$organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAll();
}
elseif ($request->getMethod() == 'GET') {
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$organizer = $em->getRepository('AppBundle:Organizer')->findAllOrderedByName($searchTerm);
}
$response = new JsonResponse();
$results = array();
foreach ($organizer as $value) {
$results[] = json_encode($value);
}
return $response->setData(array(
'results' => $results
));
}
and here's the script for the search:
$(document).ready( function(event) {
$("#search").submit(function(event) {
event.preventDefault(); //prvent default submission event
$form = $(this);
var data = $('#search_term').val();
$.ajax({
url: '/ajax',
type: "GET",
data: {'search' : data },
success: function(response){
var output = '';
for (var i = 0; i < response.length; i++) {
output[i] = output + response;
}
$('#ajax_results').html('<tr><td>' + response.id + '</td></tr>' + '<tr><td>' + response.name + '</td></tr>' + '<tr><td>' + response.dueDate + '</td></tr>');
}
})
});
});
and the index.html.twig file for displaying the data:
{% extends 'base.html.twig' %}
{% block body %}
<h2 class="page-header"> Latest events </h2>
<form id="search" method="GET" action="">
<input type="text" name="search" id="search_term" />
<input type="submit" name="submit" value="Search" />
</form>
<hr />
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Event</th>
<th>Due Date</th>
<th></th>
</tr>
</thead>
<tbody id="ajax_results">
{% for Events in organizer %}
<tr>
<th scope="row">{{Events.id}}</th>
<td>{{Events.name}}</td>
<td>{{Events.dueDate|date('j F, Y, g:i a')}}</td>
<td>
View
Edit
Delete
</td>
</tr>
{% endfor %}
<table class="table table-striped">
{% if organizer|length > 0 %}
{% for items in organizer %}
{% endfor %}
{% else %}
<tr>
<td colspan="2">No matching results found!</td>
</tr>
{% endif %}
</table>
</tbody>
</table>
{% endblock %}
Lets try to refactor your code first. Perhaps it will bring you near the solution.
public function ajaxListAction(Request $request){
$searchTerm = $request->get('search');
//don't need form here
if($searchTerm == ''){
$organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAll();
}else{
//repository should search by searchterm in next step
$organizer = $this->getDoctrine()->getRepository('AppBundle:Organizer')->findAllOrderedByName($searchTerm);
}
return new JsonResponse($organizer);
}
and javascript:
$(document).ready( function(event) {
$("#search").submit(function(event) {
event.preventDefault(); //prvent default submission event
$form = $(this);
var data = $('#search_term').val();
$.ajax({
url: '/ajax',
type: "GET",
data: {'search' : data },
success: function(response){
$('#ajax_results').html('');
$.each(response, function(key, value) {
console.log(key, value);
$('#ajax_results').append('<tr><td>' + response[key].id + '</td></tr>' + '<tr><td>' + response[key].name + '</td></tr>' + '<tr><td>' + response[key].dueDate + '</td></tr>');
});
}
})
});
});
Please tell what do you see in js console after submit the search?
I managed to make it work. The problem was that I didn't have all the fields sent into the array in the jsonSerialize() method in the Entity file and thus the fields were showing undefined.
I also completed the append method in the .js file in order to have the whole markup replicated upon the ajax call.
Thanks to Rawburner for the suggestions!
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);
}
});
});
});