Problem passing PHP variable to an AJAX file using json_encode - php

Working on a form which has got 3 phases. In phase 1 the user fills a form which is submitted to the backend for validation, some data computation and later passed to the 2nd phase where the user triggers a button which has a dynamic id. Next, I use AJAX to fetch the values the user entered in the 1st phase of the form to a final controller.
I store all the values the user entered in a PHP variable called oldata but when I try json_encode() the variable inside the AJAX code and log the values in console tab I dont get the data from the form.
Phase 1
<form method="POST" action="{{ route('b2c.getplans') }}" class="form-contact" accept-charset="UTF-8">
<div class="form-line{{ $errors->has('FirstName') ? ' has-error' : '' }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text-area" class="form-input" name="FirstName" id="FirstName" value="{{ old('FirstName') }}" required>
<label>First Name *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('FirstName'))
<span class="help-block">
<strong>{{ $errors->first('FirstName') }}</strong>
</span>
#endif
</div>
<div class="form-line{{ $errors->has('MiddleName') ? ' has-error' : '' }}">
<input type="text-area" class="form-input" name="MiddleName" id="MiddleName" value="{{ old('MiddleName') }}" required>
<label>Middle Name *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('MiddleName'))
<span class="help-block">
<strong>{{ $errors->first('MiddleName') }}</strong>
</span>
#endif
</div>
<div class="form-line registar love {{ $errors->has('email') ? ' has-error' : '' }}" style="margin-left: 0px;">
<input type="text-area" id="email" class="form-input" name="email" value="{{ old('email') }}" required>
<label>Email *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div class="form-line {{ $errors->has('phone') ? ' has-error' : '' }}">
<input type="text-area" class="form-input" name="phone" id="phone" value="{{ old('phone') }}" required>
<label>Phone Number *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('phone'))
<span class="help-block">
<strong>{{ $errors->first('phone') }}</strong>
</span>
#endif
</div>
<div class="form-line {{ $errors->has('dob') ? ' has-error' : '' }}">
<input type="date" class="form-input" name="dob" value="{{ old('dob') }}" required>
<label>Date of Birth *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('dob'))
<span class="help-block">
<strong>{{ $errors->first('dob') }}</strong>
</span>
#endif
</div>
<button type="submit" class="form-b3c" style="cursor:pointer;"> Get Plans</button>
</form>
Controller to handle phase 1
//Post Request of plan entries
public
function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'FirstName' => 'required|string|min:2',
'MiddleName' => 'required|string|min:2',
'phone' => 'required|string|max:20',
'dob' => 'required|valid_birth_date',
'email' => 'required|string|email|max:255',
]
);
//fetches all the unput values from the form
$oldata = $request->all();
$plans_benefits = view("B2C::travel.plans", compact(oldata))->render();
return $plans_benefits;
}
Phase 2
#if (!empty($plans_benefits))
<div class="container">
<div class="PLAN">
<main class="top">
<div class="row">
#foreach ($plans_benefits as $plan_benefits)
#php
$plan_data = $plan_benefits[0];
$benefits = $plan_benefits[1];
$plan_name = $plan_data->Calculation_TravelPlan->TravelPlan->Name;
#endphp
<div class="card plan">
<h5 class="card-title plan"> {{$plan_name}} </h5>
<img class="card-img-top plan" src="{{asset('assets/images-new/superior.svg')}}" alt="Card image cap">
<div class="card-body">
<div class="travel-plan">
<div class="superior-content">
<table class="table">
<tbody>
#foreach($benefits as $benefit)
<tr>
<td class="plan-title">{{$benefit->name}}</td>
#if($benefit->value == 'true')
<td class="plan-worth"><i class="fas fa-check"></i></td>
#elseif ($benefit->value == 'false')
<td class="plan-worth"><i class="fas"></i></td>
#else
<td class="plan-worth"> {{$benefit->value}} </td>
#endif
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<!-- Hiden-->
<input type="hidden" value="{{$plan_data->CalculationId}}"" class ="calc_id" name="calc_id" id="calc_id{{$plan_data->CalculationId}}"/>
<input type="hidden" value="{{$plan_name}}" class ="travelplan" name="travelplan" id="plan{{$plan_data->CalculationId}}"/>
<!--Hidden-->
<p class="card-text plan">TOTAL
<span class="amount">$ {{round($plan_data->TravelBasicPremium,2)}}
</span>
</p>
<!-- AJAX call when the button is hit-->
<a id ="{{$plan_data->CalculationId}}" class="plan-quote get_quote" style="cursor:pointer;"><span>Get Quote</span></a>
</div>
</div>
#endforeach
</div>
</main>
</div>
</div>
#endif
AJAX code
$('.PLAN').on('click', '.get_quote', function () {
var olddata = {!! json_encode($oldata) !!};
console.log(oldata);
var entries = oldata.serialize();
$.ajax({
//URL from routes file in Laravel
url: 'getquote',
//GET request
type: 'get',
contentType: 'application/x-www-form-urlencoded',
data: entries + '&calc_id=' + c_id + '&travelplan=' + plan_name,
success: function success(response) {
console.log(response);
},
error: function error(data) {
console.log(data);
}
});
//END AJAX REQUEST

Set dataType in your ajax code.
$.ajax({
url: 'getquote',
type: 'get',
dataType: "json"
...
)};
Hope it will help.

Related

Laravel update function doesn't work and no error shown

I'm trying to update my database record with simple query in laravel controller.
This is my code,
DB::table('calender_events')->where('id', '=', '1')->update(
array(
'title' => $request->title,
)
);
form
<form id="addEventForm" method="post" action="{{ route('editEvent.store') }}" autocomplete="off">
#csrf
<div class="pl-lg-4">
<div class="form-group{{ $errors->has('title') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-title">{{ __('Title') }}</label>
<div class="row">
<div class="col">
<input type="text" name="title" id="input-title" class="form-control form-control-alternative{{ $errors->has('title') ? ' is-invalid' : '' }}" placeholder="{{ __('Title') }}" value="{{ $old_event['title'] }}" required autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current Title: {{ $old_event['title'] }}</p>
</div>
</div>
#if ($errors->has('title'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary mt-4">{{ __('Save') }}</button>
</div>
</div>
</form>
when I click save button it redirect to home page as expected , but db doesn't get updated.
also I used insert and select queries without any error.
and yes,there is a record in database with id=1.
please help!
You should have to write the code like this
DB::table('calender_events')->where('id',1)->update(
array(
'title' => $request->title,
)
);
This is the working code I finally come up with,
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
class EditUserController extends Controller
{
/**
* Update the specified user in storage
*
* #param \App\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function update(Request $request)
{
$image = $request->file('avatar');
if($image!=null){
$avatar_name = $request->get('NIC').'.'.$image->getClientOriginalExtension();
$folder = '/uploads/avatars/';
// $filePath = $folder . $avatar_name;
$this->uploadOne($image, $folder, 'public', $avatar_name);
}else{
$avatar_name = null;
}
DB::table('users')->where('id', '=', $request->user_id_)->update(
array(
'avatar_id' => $avatar_name,
'name'=>$request->name,
'NIC'=>$request->NIC,
'email'=>$request->email,
'current_job_position'=>$request->current_job_position,
'birthday'=>$request->birthday,
'anniversary'=>$request->anniversary,
'phone_home'=>$request->phone_home,
'phone_mobile'=>$request->phone_mobile,
'address_permanent'=>$request->address_permanent,
'address_temporary'=>$request->address_temporary,
'branch'=>$request->branch,
'bank'=>$request->bank,
'bank_number'=>$request->bank_number,
'user_role'=>$request->user_role,
'supervisor_manager'=>$request->supervisor_manager,
'next_kin_name'=>$request->next_kin_name,
'next_kin_occupation'=>$request->next_kin_occupation,
'next_kin_address'=>$request->next_kin_address,
'next_kin_office_address'=>$request->next_kin_office_address,
'next_kin_phone_mobile'=>$request->next_kin_phone_mobile,
'next_kin_phone_home'=>$request->next_kin_phone_home,
'updated_at'=>now()
)
);
return redirect()->route('user.index')->withStatus(__('User successfully updated.'));
}
/**
* Store a newly created user in storage
*
* #param \App\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request)
{
$image = $request->file('avatar');
$pass = Hash::make($request->password);
if($image!=null){
$avatar_name = $request->get('NIC').'.'.$image->getClientOriginalExtension();
$folder = '/uploads/avatars/';
// $filePath = $folder . $avatar_name;
$this->uploadOne($image, $folder, 'public', $avatar_name);
DB::table('users')->insert([
[
'avatar_id' => $avatar_name,
'name'=>$request->name,
'NIC'=>$request->NIC,
'email'=>$request->email,
'password'=>$pass,
'current_job_position'=>$request->current_job_position,
'birthday'=>$request->birthday,
'anniversary'=>$request->anniversary,
'phone_home'=>$request->phone_home,
'phone_mobile'=>$request->phone_mobile,
'address_permanent'=>$request->address_permanent,
'address_temporary'=>$request->address_temporary,
'branch'=>$request->branch,
'bank'=>$request->bank,
'bank_number'=>$request->bank_number,
'user_role'=>$request->user_role,
'supervisor_manager'=>$request->supervisor_manager,
'next_kin_name'=>$request->next_kin_name,
'next_kin_occupation'=>$request->next_kin_occupation,
'next_kin_address'=>$request->next_kin_address,
'next_kin_office_address'=>$request->next_kin_office_address,
'next_kin_phone_mobile'=>$request->next_kin_phone_mobile,
'next_kin_phone_home'=>$request->next_kin_phone_home,
'created_at'=>now(),
],
]);
}else{
DB::table('users')->insert([
[
'name'=>$request->name,
'NIC'=>$request->NIC,
'email'=>$request->email,
'password'=>$pass,
'current_job_position'=>$request->current_job_position,
'birthday'=>$request->birthday,
'anniversary'=>$request->anniversary,
'phone_home'=>$request->phone_home,
'phone_mobile'=>$request->phone_mobile,
'address_permanent'=>$request->address_permanent,
'address_temporary'=>$request->address_temporary,
'branch'=>$request->branch,
'bank'=>$request->bank,
'bank_number'=>$request->bank_number,
'user_role'=>$request->user_role,
'supervisor_manager'=>$request->supervisor_manager,
'next_kin_name'=>$request->next_kin_name,
'next_kin_occupation'=>$request->next_kin_occupation,
'next_kin_address'=>$request->next_kin_address,
'next_kin_office_address'=>$request->next_kin_office_address,
'next_kin_phone_mobile'=>$request->next_kin_phone_mobile,
'next_kin_phone_home'=>$request->next_kin_phone_home,
'created_at'=>now(),
],
]);
}
return redirect()->route('user.index')->withStatus(__('User successfully created.'));
}
public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
{
$name = !is_null($filename) ? $filename : Str::random(25);
$path =storage_path('uploads/avatars/'.$filename.'');
if( Storage::exists($path)){
Storage::disk('public')->delete('uploads/avatars/'.$filename.'');
}
$file = $uploadedFile->storeAs($folder, $name, $disk);
return $file;
}
}
#extends('layouts.app')
#section('content')
#include('layouts.headers.cards')
<div class="container-fluid mt--7">
<div class="row">
<div class="col-xl-12 mb-5 mb-xl-0">
<div class="card bg-white shadow">
<div class="card-body">
<form id="addEventForm" method="post" action="{{ route('editEvent.store') }}" autocomplete="off">
#csrf
<div class="pl-lg-4">
<input type="number" name="eventId" id="input-eventId" value="{{ $old_event['id'] }}" style="visibility:hidden;">
<div class="form-group{{ $errors->has('title') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-title">{{ __('Title') }}</label>
<div class="row">
<div class="col">
<input type="text" name="title" id="input-title" class="form-control form-control-alternative{{ $errors->has('title') ? ' is-invalid' : '' }}" placeholder="{{ __('Title') }}" value="{{ $old_event['title'] }}" required autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current Title: {{ $old_event['title'] }}</p>
</div>
</div>
#if ($errors->has('title'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('description') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-description">{{ __('Description') }}</label>
<div class="row">
<div class="col">
<input type="text" name="description" id="input-description" class="form-control form-control-alternative{{ $errors->has('description') ? ' is-invalid' : '' }}" placeholder="{{ __('Description') }}" value="{{ $old_event['description'] }}" required autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current Description: {{ $old_event['description'] }}</p>
</div>
</div>
#if ($errors->has('description'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('description') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('startTime') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-startTime">{{ __('Start Time') }}</label>
<div class="row">
<div class="col">
<input type="time" name="startTime" id="input-startTime" class="form-control form-control-alternative{{ $errors->has('startTime') ? ' is-invalid' : '' }}" placeholder="{{ __('Start Time') }}" value="{{ old('startTime') }}" autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current Start time: {{ $old_event['startTime'] }}</p>
</div>
</div>
#if ($errors->has('startTime'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('startTime') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('endTime') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-endTime">{{ __('End Time') }}</label>
<div class="row">
<div class="col">
<input type="time" name="endTime" id="input-endTime" class="form-control form-control-alternative{{ $errors->has('endTime') ? ' is-invalid' : '' }}" placeholder="{{ __('End Time') }}" value="{{ old('endTime') }}" autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current End time: {{ $old_event['endTime'] }}</p>
</div>
</div>
#if ($errors->has('endTime'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('endTime') }}</strong>
</span>
#endif
</div>
<fieldset style="border:groove;padding:5px;">
<legend style="font-size:12px;"> &nbsp&nbsp&nbsp&nbsp One day event (set this values only for one day event)</legend>
<div class="form-group{{ $errors->has('start') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-start">{{ __('Start') }}</label>
<div class="row">
<div class="col">
<input type="date" name="start" id="input-start" class="form-control form-control-alternative{{ $errors->has('start') ? ' is-invalid' : '' }}" placeholder="{{ __('Start') }}" autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current Start date: {{ $old_event['start'] }}</p>
</div>
</div>
#if ($errors->has('start'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('start') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('end') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-end">{{ __('End') }}</label>
<div class="row">
<div class="col">
<input type="date" name="end" id="input-end" class="form-control form-control-alternative{{ $errors->has('end') ? ' is-invalid' : '' }}" placeholder="{{ __('End') }}" autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current End date: {{ $old_event['end'] }}</p>
</div>
</div>
#if ($errors->has('end'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('end') }}</strong>
</span>
#endif
</div>
</fieldset>
<fieldset style="border:groove;padding:5px;">
<legend style="font-size:12px;"> &nbsp&nbsp&nbsp&nbsp Recurring event (set this values if event is recurring)</legend>
<div class="form-group{{ $errors->has('startRecur') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-startRecur">{{ __('Start Recurring') }}</label>
<div class="row">
<div class="col">
<input type="date" name="startRecur" id="input-startRecur" class="form-control form-control-alternative{{ $errors->has('startRecur') ? ' is-invalid' : '' }}" placeholder="{{ __('Start Recurring') }}" value="{{ old('startRecur') }}" autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current Start date: {{ $old_event['startRecur'] }}</p>
</div>
</div>
#if ($errors->has('startRecur'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('startRecur') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('endRecur') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-endRecur">{{ __('End Recurring') }}</label>
<div class="row">
<div class="col">
<input type="date" name="endRecur" id="input-endRecur" class="form-control form-control-alternative{{ $errors->has('endRecur') ? ' is-invalid' : '' }}" placeholder="{{ __('End Recurring') }}" value="{{ old('endRecur') }}" autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current End date: {{ $old_event['endRecur'] }}</p>
</div>
</div>
#if ($errors->has('endRecur'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('endRecur') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('daysOfWeek') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-daysOfWeek">{{ __('Days of week') }}</label>
<div class="row">
<div class="col">
<select multiple size="7" name="daysOfWeek[]" id="input-daysOfWeek" class="form-control form-control-alternative{{ $errors->has('daysOfWeek') ? ' is-invalid' : '' }}" placeholder="{{ __('days Of Week') }}" autofocus>
<option value="0">Sunday</option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
</select>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current selected days: {{ $old_event['daysOfWeek'] }}</p>
</div>
</div>
#if ($errors->has('daysOfWeek'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('daysOfWeek') }}</strong>
</span>
#endif
</div>
</fieldset>
<div class="form-group{{ $errors->has('assignesto') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-assignesto">{{ __('assignes to') }}</label>
<div class="row">
<div class="col">
<select multiple size="3" name="assignesto[]" id="input-assignesto" class="form-control form-control-alternative{{ $errors->has('assignesto') ? ' is-invalid' : '' }}" placeholder="{{ __('assignesto') }}" required autofocus>
#foreach($assignees_array as $key)
<option value="{{ $key->id }}">{{ $key->name }}</option>
#endforeach
</select>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current assignees: {{ $old_event['assigned_to_string'] }}</p>
</div>
</div>
#if ($errors->has('assignesto'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('assignesto') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('location') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-location">{{ __('location') }}</label>
<div class="row">
<div class="col">
<input type="text" name="location" id="input-location" class="form-control form-control-alternative{{ $errors->has('location') ? ' is-invalid' : '' }}" placeholder="{{ __('location') }}" value="{{ $old_event['location'] }}" required autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current Location: {{ $old_event['location'] }}</p>
</div>
</div>
#if ($errors->has('location'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('location') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('notes') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-notes">{{ __('notes') }}</label>
<div class="row">
<div class="col">
<input type="text" name="notes" id="input-notes" class="form-control form-control-alternative{{ $errors->has('notes') ? ' is-invalid' : '' }}" placeholder="{{ __('notes') }}" value="{{ $old_event['notes'] }}" required autofocus>
</div>
<div class="col">
<p style="font-size:14px;padding: 10px;">Current Notes: {{ $old_event['notes'] }}</p>
</div>
</div>
#if ($errors->has('notes'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('notes') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('notes') ? ' has-danger' : '' }}">
<p style="font-size:14px;padding: 10px;">Event created by: {{ $old_event['assigned_by_detail'] }}</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary mt-4">{{ __('Save') }}</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
</script>
#include('layouts.footers.auth')
</div>
#endsection
#push('js')
<script src="{{ asset('argon') }}/vendor/chart.js/dist/Chart.min.js"></script>
<script src="{{ asset('argon') }}/vendor/chart.js/dist/Chart.extension.js"></script>
#endpush
I had to make another blade and move edit functions to another controller.And this was because of free dashboard template I'm using.It has built in authentication functions but blocks some parts for free users.Anyway thanks for your help.

how can i get the values of some inputs from database after select option in dropdown

I'm building an HTML form that contains all information about clients, and the others information, so I would when I choose the name of the client that is in the dropdown (select options that contain all name of clients ) the other input fields like (address, tel, email) should be filled automatically.
I don't know what I have to use ajax or jquery and how to use it.
this is my view:
#extends('layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-11">
<div class="panel panel-default">
<div class="panel-heading">Création de commandes</div>
<div class="panel-body">
<form id="form2" class="form-horizontal" method="POST" action="{{url('gestion_commandes/create')}}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('nomp') ? ' has-error' : '' }}">
<label for="nomp" class="col-md-1 control-label">Client</label>
<div class="col-md-5">
<select name="nomclient" id="nomclient" class="form-control dynamic" data-dependent="organisme" required autofocus>
<option>--Select--</option>
#foreach ($clientscombos as $clientcombos)
<option value="{{$clientcombos->nom}}">{{$clientcombos->nom}} </option>
#endforeach
</select>
</div>
{{ csrf_field() }}
<label for="organisme" class="col-md-1 control-label">Organisme</label>
<div class="col-md-5">
<input id="organisme" type="text" class="form-control" name="organisme" value="{{$clientcombos->organisme}}" required autofocus>
#if ($errors->has('organisme'))
<span class="help-block">
<strong>{{ $errors->first('organisme') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('adresse') ? ' has-error' : '' }}">
<label for="adresse" class="col-md-1 control-label">Adresse</label>
<div class="col-md-5">
<input id="adresse" type="text" class="form-control" name="adresse" value="{{$clientcombos->adresse}}" autofocus>
#if ($errors->has('adresse'))
<span class="help-block">
<strong>{{ $errors->first('adresse') }}</strong>
</span>
#endif
</div>
<label for="emailp" class="col-md-1 control-label">E-Mail Address</label>
<div class="col-md-5">
<input id="emailp" type="email" class="form-control" name="emailp" placeholder="Saisir l'adresse email" required autofocus>
#if ($errors->has('emailp'))
<span class="help-block">
<strong>{{ $errors->first('emailp') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('adressep') ? ' has-error' : '' }}">
<label for="tel" class="col-md-1 control-label">Tel</label>
<div class="col-md-3">
<input id="tel" type="Tel" class="form-control" name="tel" value="{{$clientcombos->tel1}}" required autofocus>
#if ($errors->has('tel'))
<span class="help-block">
<strong>{{ $errors->first('tel') }}</strong>
</span>
#endif
</div>
<label for="tel2p" class="col-md-1 control-label">Tel2</label>
<div class="col-md-3">
<input id="tel2p" type="Tel" class="form-control" name="tel2p" value="+2126" required autofocus>
#if ($errors->has('tel2p'))
<span class="help-block">
<strong>{{ $errors->first('tel2p') }}</strong>
</span>
#endif
</div>
<label for="faxp" class="col-md-1 control-label">Fax</label>
<div class="col-md-3">
<input id="faxp" type="Tel" class="form-control" name="faxp" value="{{$clientcombos->fax}}" required autofocus>
#if ($errors->has('faxp'))
<span class="help-block">
<strong>{{ $errors->first('faxp') }}</strong>
</span>
#endif
</div>
</div>
<div class=" panel panel-success"> </div>
<div class=" panel panel-success"> </div>
<div class="form-group{{ $errors->has('daterecep') ? ' has-error' : '' }}">
<label for="commercial" class="col-md-1 control-label">Commercial</label>
<div class="col-md-3">
<select name="commercial" id="commercial" class="form-control" required autofocus>
<option>--Select--</option>
#foreach ($combocommerciaux as $combocommercial)
<option value="{{$combocommercial->name}}">{{$combocommercial->name}} </option>
#endforeach
</select>
</div>
<label for="datereception" class="col-md-1 control-label">Date de réception</label>
<div class="col-md-3">
<input id="datereception" type="date" class="form-control" name="datereception" placeholder="Saisir le nom complet" required autofocus>
#if ($errors->has('datereception'))
<span class="help-block">
<strong>{{ $errors->first('datereception') }}</strong>
</span>
#endif
</div>
<label for="dateprelev" class="col-md-1 control-label">Date de prélevement</label>
<div class="col-md-3">
<input id="dateprelev" type="date" class="form-control" name="dateprelev" placeholder="Saisir le nom complet" required autofocus>
#if ($errors->has('dateprelev'))
<span class="help-block">
<strong>{{ $errors->first('dateprelev') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('commercial') ? ' has-error' : '' }}">
<label for="savedby" class="col-md-9 control-label">Enregistrée par </label>
<div class="col-md-3">
<input id="savedby" type="text" class="form-control" name="savedby" value="{{Auth::user()->name}}" required autofocus>
#if ($errors->has('savedby'))
<span class="help-block">
<strong>{{ $errors->first('savedby') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('nbrrowsol') ? ' has-error' : '' }}">
<label for="nbrrowsow" class="col-md-1 control-label">Sol </label>
<div class="col-md-3">
<input id="nbrrowsol" type="number" class="form-control" name="nbrrowsol" required autofocus>
#if ($errors->has('nbrrowsol'))
<span class="help-block">
<strong>{{ $errors->first('nbrrowsol') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('nbrroweau') ? ' has-error' : '' }}">
<label for="nbrroweau" class="col-md-1 control-label">Eau </label>
<div class="col-md-3">
<input id="nbrroweau" type="number" class="form-control" name="nbrroweau" required autofocus>
#if ($errors->has('nbrroweau'))
<span class="help-block">
<strong>{{ $errors->first('nbrroweau') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('nbrrowveg') ? ' has-error' : '' }}">
<label for="nbrrowveg" class="col-md-1 control-label">VEG </label>
<div class="col-md-3">
<input id="nbrrowveg" type="number" class="form-control" name="nbrrowveg" required autofocus>
#if ($errors->has('nbrrowveg'))
<span class="help-block">
<strong>{{ $errors->first('nbrrowveg') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('nbrrowbiof') ? ' has-error' : '' }}">
<label for="nbrrowbiof" class="col-md-1 control-label">Fertilisant </label>
<div class="col-md-3">
<input id="nbrrowbiof" type="number" class="form-control" name="nbrrowbiof" placeholder="Saisir l'adresse email" required autofocus>
#if ($errors->has('nbrrowbiof'))
<span class="help-block">
<strong>{{ $errors->first('nbrrowbiof') }}</strong>
</span>
#endif
</div>
<div class="col-md-6 control-label">
<button type="submit" class="btn btn-primary" onclick="location.href='{{url('gestion_regions/create')}}'" >Executer</button>
</div>
</div>
<div class="form-group{{ $errors->has('nbrrowmicair') ? ' has-error' : '' }}">
<label for="nbrrowmicair" class="col-md-1 control-label">Mic Air </label>
<div class="col-md-3">
<input id="nbrrowmicair" type="number" class="form-control" name="nbrrowmicair" required autofocus>
#if ($errors->has('nbrrowmicair'))
<span class="help-block">
<strong>{{ $errors->first('nbrrowmicair') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('nbrrowmiceau') ? ' has-error' : '' }}">
<label for="nbrrowmiceau" class="col-md-1 control-label">Mic Eau</label>
<div class="col-md-3">
<input id="nbrrowmiceau" type="number" class="form-control" name="nbrrowmiceau" required autofocus>
#if ($errors->has('nbrrowmiceau'))
<span class="help-block">
<strong>{{ $errors->first('nbrrowmiceau') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('nbrrowmicsurface') ? ' has-error' : '' }}">
<label for="nbrrowmicsurface" class="col-md-1 control-label">Mic Surface </label>
<div class="col-md-3">
<input id="nbrrowmicsurface" type="number" class="form-control" name="nbrrowmicsurface" placeholder="Saisir l'adresse email" required autofocus>
#if ($errors->has('nbrrowmicsurface'))
<span class="help-block">
<strong>{{ $errors->first('nbrrowmicsurface') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-success">
Enregistrer
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
this is controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Client;
class DynamicDependent extends Controller
{
public function comboboxclients()
{
$clientscombos = DB::select('select * from clients');
$combocommerciaux = DB::select('select * from commercials');
return view('gestion_commandes.create',['clientscombos' => $clientscombos , 'combocommerciaux' => $combocommerciaux]);
}
}
You have to:
1) Server-side: create another action which will fetch client data based on value from select(I suggest you using an client id as select value inside your template).
2) Client-side: add hook on select value change('change' event inside JS), which will send an AJAX request(containing selected value) to action created on step 1, and populate form inputs with received data.
That's pretty much it. Fell free to ask about specific implementation details, but keep in mind that no one will write code for you here, you have to do it yourself, but you'll be fine with this directions.

Error when fetching values via AJAX request in a multi-step form in Laravel

I am creating a multi-step page form in a Laravel application whereby I want to carry the values the user entered in the 1st phase of the form to the 3rd phase of the form through AJAX (when the user hits submit button on the 2nd phase of the form an AJAX call is triggered and use the values in a final controller). But it aint working. Please assist?
First Phase of the form
<form method="POST" action="{{ route('b2c.getplans') }}" class="form-contact" accept-charset="UTF-8">
<div class="form-line{{ $errors->has('FirstName') ? ' has-error' : '' }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text-area" class="form-input" name="FirstName" id="FirstName" value="{{ old('FirstName') }}" required>
<label>First Name *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('FirstName'))
<span class="help-block">
<strong>{{ $errors->first('FirstName') }}</strong>
</span>
#endif
</div>
<div class="form-line{{ $errors->has('MiddleName') ? ' has-error' : '' }}">
<input type="text-area" class="form-input" name="MiddleName" id="MiddleName" value="{{ old('MiddleName') }}" required>
<label>Middle Name *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('MiddleName'))
<span class="help-block">
<strong>{{ $errors->first('MiddleName') }}</strong>
</span>
#endif
</div>
<div class="form-line {{ $errors->has('LastName') ? ' has-error' : '' }}">
<input type="text-area" class="form-input" id="LastName" name="LastName" value="{{ old('LastName') }}" required>
<label>Surname *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('LastName'))
<span class="help-block">
<strong>{{ $errors->first('LastName') }}</strong>
</span>
#endif
</div>
<div class="form-line registar love {{ $errors->has('email') ? ' has-error' : '' }}" style="margin-left: 0px;">
<input type="text-area" id="email" class="form-input" name="email" value="{{ old('email') }}" required>
<label>Email *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div class="form-line {{ $errors->has('phone') ? ' has-error' : '' }}">
<input type="text-area" class="form-input" name="phone" id="phone" value="{{ old('phone') }}" required>
<label>Phone Number *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('phone'))
<span class="help-block">
<strong>{{ $errors->first('phone') }}</strong>
</span>
#endif
</div>
<div class="form-line {{ $errors->has('dob') ? ' has-error' : '' }}">
<input type="date" class="form-input" name="dob" value="{{ old('dob') }}" required>
<label>Date of Birth *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('dob'))
<span class="help-block">
<strong>{{ $errors->first('dob') }}</strong>
</span>
#endif
</div>
<div class="form-line registar move {{ $errors->has('country-residence') ? ' has-error' : '' }}" style='margin-left: 0px;'>
<select name="country-residence" id="country-residence" class="form-input" required>
<option selected disabled> </option>
#foreach($countries as $country)
<option value='{{ $country->phonecode }}'> {{ $country->nicename }} </option>
#endforeach
</select>
<label>Country of Residence *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('country-residence'))
<span class="help-block">
<strong>{{ $errors->first('country-residence') }}</strong>
</span>
#endif
</div>
<div class="form-line registar move {{ $errors->has('destination-country') ? ' has-error' : '' }}">
<select name="destination-country" id="destination-country" class="form-input" required>
<option selected disabled> </option>
#foreach($countries as $country)
<option value='{{ $country->phonecode }}'> {{ $country->nicename }} </option>
#endforeach
</select>
<label>Country of Destination *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('destination-country'))
<span class="help-block">
<strong>{{ $errors->first('destination-country') }}</strong>
</span>
#endif
</div>
<button type="submit" class="form-b3c" style="cursor:pointer;"> Get Plans</button>
</form>
2nd Phase of the form
<!-- Phase 2-->
#extends('B2C::layouts.app')
#section('content')
#if (!empty($plans_benefits))
<div class="container">
<div class="PLAN">
<main class="top">
<div class="row">
#foreach ($plans_benefits as $plan_benefits)
#php
$plan_data = $plan_benefits[0];
$benefits = $plan_benefits[1];
$plan_name = $plan_data->Calculation_TravelPlan->TravelPlan->Name;
#endphp
<div class="card plan">
<h5 class="card-title plan"> {{$plan_name}} </h5>
<img class="card-img-top plan" src="{{asset('assets/images-new/superior.svg')}}" alt="Card image cap">
<div class="card-body">
<div class="travel-plan">
<div class="superior-content">
<table class="table">
<tbody>
#foreach($benefits as $benefit)
<tr>
<td class="plan-title">{{$benefit->name}}</td>
#if($benefit->value == 'true')
<td class="plan-worth"><i class="fas fa-check"></i></td>
#elseif ($benefit->value == 'false')
<td class="plan-worth"><i class="fas"></i></td>
#else
<td class="plan-worth"> {{$benefit->value}} </td>
#endif
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<!-- Hiden-->
<input type="hidden" value="{{$plan_data->CalculationId}}"" class ="calc_id" name="calc_id" id="calc_id{{$plan_data->CalculationId}}"/>
<input type="hidden" value="{{$plan_name}}" class ="travelplan" name="travelplan" id="plan{{$plan_data->CalculationId}}"/>
<!--Hidden-->
<p class="card-text plan">TOTAL
<span class="amount">$ {{round($plan_data->TravelBasicPremium,2)}}
</span>
</p>
<!-- AJAX call when the button is hit-->
<a id ="{{$plan_data->CalculationId}}" class="plan-quote get_quote" style="cursor:pointer;"><span>Get Quote</span></a>
</div>
</div>
#endforeach
</div>
</main>
</div>
</div>
#endif
#endsection
<!-- END PHASE 2-->
AJAX CODE to fetch values when the button in the above form is hit
$('.PLAN').on('click', '.get_quote', function () {
//Fetch inputs from form
var inputs = $(".form-contact :input");
var calc_id = $(this).attr('id');
var c_id = $('#calc_id' + calc_id).val();
var plan_name = $('#plan' + calc_id).val();
var entries = inputs.serialize();
$.ajax({
//URL from routes file in Laravel
url: 'getquote',
//GET request
type: 'get',
contentType: 'application/x-www-form-urlencoded',
data: entries + '&calc_id=' + c_id + '&travelplan=' + plan_name,
success: function success(response) {
console.log(response);
$('.quote').html(response);
$tab_active = $progressWizard.find('.active');
$tab_active.next().removeClass('disabled');
$tab_next = $tab_active.next().find('a[data-toggle="tab"]');
triggerClick($tab_next);
},
error: function error(data) {
console.log(data);
}
});
//END AJAX REQUEST
Routes file for get quote
Route::get( '/getquote', 'B2CController#createQuote');
Final controller to use the values fetched via AJAX code
//Get quotes
public
function createQuote(Request $request)
{
//Optional validation
$validation = $this->validate($request, [
'firstname' => 'required|string|min:2',
'middlename' => 'required|string|min:2',
'surname' => 'required|string|min:2',
'country-residence' => 'required',
'phone' => 'required|string|max:20|regex:/[2547]{4}[0-9]{8}/',
'destination-country' => 'required',
'dob' => 'required',
'departure_date' => 'required',
'return_date' => 'required',
'email' => 'required|string|email|max:255',
'calc_id' => 'required',
'travelplan' => 'required',
'cover_options' => 'required',
]);
//Using GuzzleHttp to POST values
$client = new Client();
$quote = $client->post(route('api.user.createQuote'), [
'json' => [
'DobPrincipalTraveller' => $request->dob,
'TravelStartDate' => $request->departure_date,
'TravelEndDate' => $request->return_date,
'CoverOption' => $request->cover_options,
'WithSpouse' => 0,
'FirstName' => $request->firstname,
'MiddleName' => $request->middlename,
'LastName' => $request->surname,
'ClientEmail' => $request->email,
'ContactNumber' => $request->phone,
'CalculationId' => $request->calc_id,
'TravelPlan' => $request->travelplan,
],
"http_errors" => false,
]);
$quote_data = json_decode($quote->getBody()->getContents())->data;
$quoteholder_name = $request->firstname . ' ' . $request->middlename . ' ' . $request->surname;
$quoteholder_email = $request->email;
$travel_plan = $request->travelplan;
$quote_data = view("B2C::travel.quote", compact('quote_data', 'quoteholder_name', 'quoteholder_email', 'travel_plan'))->render();
return $quote_data;
}
Change your $request->{paramName} statements to $request->input('{paramName}') like this:
...
'DobPrincipalTraveller' => $request->input('dob'),
'TravelStartDate' => $request->input('departure_date'),
'TravelEndDate' => $request->input('return_date'),
'CoverOption' => $request->input('cover_options'),
...
Read more about accessing parameters from the request object here: https://laravel.com/docs/5.7/requests#retrieving-input

Problem parsing values in a Multi-step form using AJAX

Working on a multi-step form which has got 3 phases. In phase 1 the user fills a form which is submitted to the backend for validation, some data computation and later passed to the 2nd phase where the user triggers a button which has a dynamic id. Next, I use AJAX to fetch the values the user entered in the 1st phase of the form and the unique id of the button clicked by the user in the 2nd phase to a final controller.
The problem is the AJAX request aint picking the values from the 1st phase of the form when I try using dd($quote) as shown in the code below.
Phase 1
<form method="POST" action="{{ route('b2c.getplans') }}" class="form-contact" accept-charset="UTF-8">
<div class="form-line{{ $errors->has('FirstName') ? ' has-error' : '' }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text-area" class="form-input" name="FirstName" id="FirstName" value="{{ old('FirstName') }}" required>
<label>First Name *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('FirstName'))
<span class="help-block">
<strong>{{ $errors->first('FirstName') }}</strong>
</span>
#endif
</div>
<div class="form-line{{ $errors->has('MiddleName') ? ' has-error' : '' }}">
<input type="text-area" class="form-input" name="MiddleName" id="MiddleName" value="{{ old('MiddleName') }}" required>
<label>Middle Name *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('MiddleName'))
<span class="help-block">
<strong>{{ $errors->first('MiddleName') }}</strong>
</span>
#endif
</div>
<div class="form-line registar love {{ $errors->has('email') ? ' has-error' : '' }}" style="margin-left: 0px;">
<input type="text-area" id="email" class="form-input" name="email" value="{{ old('email') }}" required>
<label>Email *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div class="form-line {{ $errors->has('phone') ? ' has-error' : '' }}">
<input type="text-area" class="form-input" name="phone" id="phone" value="{{ old('phone') }}" required>
<label>Phone Number *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('phone'))
<span class="help-block">
<strong>{{ $errors->first('phone') }}</strong>
</span>
#endif
</div>
<div class="form-line {{ $errors->has('dob') ? ' has-error' : '' }}">
<input type="date" class="form-input" name="dob" value="{{ old('dob') }}" required>
<label>Date of Birth *</label>
<div class="error-label">Field is required!</div>
<div class="check-label"></div>
#if ($errors->has('dob'))
<span class="help-block">
<strong>{{ $errors->first('dob') }}</strong>
</span>
#endif
</div>
<button type="submit" class="form-b3c" style="cursor:pointer;"> Get Plans</button>
</form>
2nd phase of the form
#if (!empty($plans_benefits))
<div class="container">
<div class="PLAN">
<main class="top">
<div class="row">
#foreach ($plans_benefits as $plan_benefits)
#php
$plan_data = $plan_benefits[0];
$benefits = $plan_benefits[1];
$plan_name = $plan_data->Calculation_TravelPlan->TravelPlan->Name;
#endphp
<div class="card plan">
<h5 class="card-title plan"> {{$plan_name}} </h5>
<img class="card-img-top plan" src="{{asset('assets/images-new/superior.svg')}}" alt="Card image cap">
<div class="card-body">
<div class="travel-plan">
<div class="superior-content">
<table class="table">
<tbody>
#foreach($benefits as $benefit)
<tr>
<td class="plan-title">{{$benefit->name}}</td>
#if($benefit->value == 'true')
<td class="plan-worth"><i class="fas fa-check"></i></td>
#elseif ($benefit->value == 'false')
<td class="plan-worth"><i class="fas"></i></td>
#else
<td class="plan-worth"> {{$benefit->value}} </td>
#endif
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<!-- Hiden-->
<input type="hidden" value="{{$plan_data->CalculationId}}"" class ="calc_id" name="calc_id" id="calc_id{{$plan_data->CalculationId}}"/>
<input type="hidden" value="{{$plan_name}}" class ="travelplan" name="travelplan" id="plan{{$plan_data->CalculationId}}"/>
<!--Hidden-->
<p class="card-text plan">TOTAL
<span class="amount">$ {{round($plan_data->TravelBasicPremium,2)}}
</span>
</p>
<!-- AJAX call when the button is hit-->
<a id ="{{$plan_data->CalculationId}}" class="plan-quote get_quote" style="cursor:pointer;"><span>Get Quote</span></a>
</div>
</div>
#endforeach
</div>
</main>
</div>
</div>
#endif
AJAX code to fetch values when the button in the 2nd phase is hit
$('.PLAN').on('click', '.get_quote', function () {
//Fetch inputs from form
var inputs = $(".form-contact :input");
var calc_id = $(this).attr('id');
var c_id = $('#calc_id' + calc_id).val();
var plan_name = $('#plan' + calc_id).val();
var entries = inputs.serialize();
$.ajax({
//URL from routes file in Laravel
url: 'getquote',
//GET request
type: 'get',
contentType: 'application/x-www-form-urlencoded',
data: entries + '&calc_id=' + c_id + '&travelplan=' + plan_name,
success: function success(response) {
console.log(response);
},
error: function error(data) {
console.log(data);
}
});
//END AJAX REQUEST
Final controller to use values fetched via the AJAX request above
//Get quotes
public
function createQuote(Request $request)
{
//Optional validation
$validation = $this->validate($request, [
'firstname' => 'required|string|min:2',
'middlename' => 'required|string|min:2',
'phone' => 'required|string|max:20|regex:/[2547]{4}[0-9]{8}/',
'dob' => 'required',
]);
//Using GuzzleHttp to post values
$client = new Client();
$quote = $client->post(route('api.user.createQuote'), [
'json' => [
'FirstName' => $request->firstname,
'MiddleName' => $request->middlename,
'phone' => $request->phone,
'dob' => $request->dob,
],
"http_errors" => false,
]);
dd($quote);
}

Using Datatables in Laravel

Hello I'm using Datatables on my laravel App from https://datatables.yajrabox.com/eloquent/add-edit-remove-column
In my code, I've got the edit buttons under the Action column to serve as data toggles for a modal which holds a form.
Now I'm trying to populate the modal with data from the table row with the currently clicked edit button. What would be the best way to go about this. I've tried several ways to no avail, including trying to use jquery to get the values of the sibling elements and put them into respective input fields in the modal form. I've also tried calling a method in my controller to find the relevant user and return it to the view, before returning the markup for the edit button. All to no avail.below is my code, what would be the best way to go about this?
Kind regards
my view:
#extends('layouts.master')
<?php
echo $_GET['edit-2'];
?>
#section('content')
<table class="table table-bordered" id="users-table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>Updated At</th>
<th>Action</th>
</tr>
</thead>
</table>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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" id="myModalLabel">New Student</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" method="POST" action="/createStudent">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">FullName</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="" required autofocus> #if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required> #if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group{{ $errors->has('phone') ? ' has-error' : '' }}">
<label for="phone" class="col-md-4 control-label">Phone Number</label>
<div class="col-md-6">
<input id="phone" type="text" class="form-control" name="phone" required> #if ($errors->has('phone'))
<span class="help-block">
<strong>{{ $errors->first('phone') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group">
<label for="DOB" class="col-md-4 control-label">Date of Birth</label>
<div class="col-md-6">
<input id="DOB" type="date" class="form-control" name="DOB" required>
</div>
</div>
<fieldset class="offset-4">
<div class="form-group">
<label class="col-xs-3 control-label">Gender</label>
<div class="col-xs-9">
<div class="radio">
<label>
<input id="inlineradio1" name="gender" value="male" type="radio">
Male</label>
</div>
<div class="radio">
<label>
<input id="inlineradio1" name="gender" value="female" type="radio">
Female</label>
</div>
</div>
</div>
</fieldset>
<div class="form-group{{ $errors->has('phone') ? ' has-error' : '' }}">
<label for="qualification" class="col-md-4 control-label">Qualification</label>
<div class="col-md-6">
<input id="qualification" type="text" class="form-control" name="qualification" required> #if ($errors->has('qualification'))
<span class="help-block">
<strong>{{ $errors->first('qualification') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group{{ $errors->has('course') ? ' has-error' : '' }}">
<label for="Course" class="col-md-4 control-label">Course</label>
<div class="col-md-6">
<input id="course" type="text" class="form-control" name="course" required> #if ($errors->has('phone'))
<span class="help-block">
<strong>{{ $errors->first('course') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}">
<label for="amount" class="col-md-4 control-label">Amount Paid</label>
<div class="col-md-6">
<input id="amount" type="number" class="form-control" name="amount" required> #if ($errors->has('amount'))
<span class="help-block">
<strong>{{ $errors->first('amount') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#stop #push('scripts')
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('
datatables.data ') !!}',
columns: [{
data: 'id',
name: 'id'
},
{
data: 'name',
name: 'name'
},
{
data: 'email',
name: 'email'
},
{
data: 'created_at',
name: 'created_at'
},
{
data: 'updated_at',
name: 'updated_at'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
}
]
});
});
</script>
#endpush
my controller method:
public function getAddEditRemoveColumnData() {
$users = User::select(['id', 'name', 'email', 'password', 'created_at', 'updated_at']);
return Datatables:: of ($users) ->
addColumn('action', function($user) {
//DatatablesController::current_user($user);
//User::current_user($user->id);
return '<a href="#edit-'.$user - > id.
'" class="btn btn-xs btn-primary" data-toggle="modal" data-target="#myModal"><i class="glyphicon glyphicon-edit"></i> Edit</a>';
}) ->
editColumn('id', 'ID: {{$id}}') ->
removeColumn('password') ->
make(true);
}
add column for edit button in datatable
return Datatables::of($User)->addColumn('action', function ($User) {
return 'id.'" class="edit-modal btn btn-circle btn-xs btn-info" title="Edit">Edit
;
})->removeColumn("id")->make(true);
now call ajax by class name(edit-modal) and gat data with sent user-id in url from controller
$(document).on('click', '.edit-modal', function() {
$('#(your form-id)').show();
$.ajax({
type: 'get',
url: "{{ url('/user/') }}/"+$(this).data('id'),
dataType: 'json',
success: function(data) {
$('your-input').val(data.id);
$('your-2-input').val(data.name);
......
},
error: function(data){
}
});
$('#(your modal-id)').modal('show');
});
Based from this link: https://datatables.net/reference/api/row().index(), you can get the index of a row.
So for the function for your edit button, you need to pass the row index to it.
Upon clicking the edit button, you can now get the data using the index that was passed to the function, and set it to the values of the inputs on your form.
I wasn't able to try this myself, but I think it will work.
Read this also: https://github.com/yajra/laravel-datatables/issues/699 :)

Categories