Problem parsing values in a Multi-step form using AJAX - php

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

Related

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 passing PHP variable to an AJAX file using json_encode

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.

sending error message laravel required inputs

so i wanted to make validation to my register form so i made all my inputs required so i can test my validation that it works or not, so this is what i used in my controller
$Message = [
'required' => 'This input is required',
];
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required',
'password' => 'required',
'UserName' => 'required',
'Phone' => 'required',
'SSN' => 'required',
'SDT' => 'required',
'Country' => 'required',
'InsuranceAmount' => 'required',
'City' => 'required',
'Location' => 'required'
], $Message);
if ($validator->fails()) {
return redirect('/admin/users/create')
->withErrors($validator)
->withInput();
}
$user = new User;
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = bcrypt(Input::get('password'));
$user->UserName = input::get('UserName');
$user->Phone = input::get('Phone');
$user->SSN = input::get('SSN');
$user->SDT = input::get('SDT');
$user->Country = input::get('Country');
$user->City = input::get('City');
$user->Location = input::get('Location');
$user->save();
return Redirect::to('/admin/users')->with('message', 'User Created');
Now if theres no errors it works fine and redirect to user list, but if a input is empty it will just redirect to the creation page whict is what i wanted but the problem is it won't send the error message with the redirect i tried dd the validator and it has all the messages fine heres my view
<form class="form-horizontal" role="form" method="POST" action="{{ Route('userstore') }}">
{!! csrf_field() !!}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">الاسم</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" value="{{ old('name') }}">
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group {{$errors->has('UserName') ? 'has-error' : ''}}">
<label class="col-md-4 control-label">اسم المستخدم</label>
<div class="col-md-6">
<input type="text" class="form-control" name="UserName" value="{{ old('UserName') }}">
#if ($errors->has('UserName'))
<span class="help-block">
<strong>{{ $errors->first('UserName') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group {{$errors->has('Phone') ? 'has-error' : ''}}">
<label class="col-md-4 control-label">رقم الجوال</label>
<div class="col-md-6">
<input type="text" class="form-control" name="Phone" value="{{old('Phone')}}">
#if ($errors->has('Phone'))
<span class="help-block">
<strong>{{ $errors->first('Phone') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group {{$errors->has('SSN') ? 'has-error' : ''}}">
<label class="col-md-4 control-label">الرقم الوطني</label>
<div class="col-md-6">
<input type="text" class="form-control" name="SSN" value="{{old('SSN')}}">
#if ($errors->has('SSN'))
<span class="help-block">
<strong>{{ $errors->first('SSN') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group {{$errors->has('SDT') ? 'has-error' : ''}}">
<label class="col-md-4 control-label">نوع الوثيقة</label>
<div class="col-md-6">
<input type="text" class="form-control" name="SDT" value="{{old('SDT')}}">
#if ($errors->has('SDT'))
<span class="help-block">
<strong>{{ $errors->first('SDT') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group {{$errors->has('Country') ? 'has-error' : ''}}">
<label class="col-md-4 control-label">الدولة</label>
<div class="col-md-6">
<select class="form-control" name="Country">
<option>الاردن</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">المدينة</label>
<div class="col-md-6">
<select class="form-control" name="City" >
<option>عمان</option>
</select>
</div>
</div>
<div class="form-group {{$errors->has('Location') ? 'has-error' : ''}}">
<label class="col-md-4 control-label">اسم الشارع</label>
<div class="col-md-6">
<input type="text" class="form-control" name="Location" value="{{old('Location')}}">
#if ($errors->has('Location'))
<span class="help-block">
<strong>{{ $errors->first('Location') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }} ltr-input">
<label class="col-md-4 control-label">البريد الإلكتروني</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }} ltr-input">
<label class="col-md-4 control-label">كلمة المرور</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }} ltr-input">
<label class="col-md-4 control-label">تأكيد كلمة المرور</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
#if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</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 pull-right">
<i class="fa fa-btn fa-user"></i> تسجيل
</button>
</div>
</div>
</form>
and btw this is laravel 5.1
I fix the problem by upgrading my project from laravel 5.1 to 5.5

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 :)

Open the BootstrapDialog edit user form with some error if a user had not filled some field value. In laravel 5.4

I am using BootstrapDialog to open a edit user form. It opens perfectly.
In my list page when a user click on edit button, it will go to controller and and fetch that user information, and at the end it will show the Dialog Box which have a form and update button.
When he/she click on update button it will call update function of its controller and validate all field and revert back to the dialog box if some error is there. Other wise close the dialog box and show a success message.
My question is when someone left blank to a field and it validate in controller, but it does not able to show the dialog box anymore. How can I show error message to the user in that Dialog box.
I am using laravel 5.4.
Edit Button
<a class="btn btn-xs btn-primary edit_user_"
id="edit_user_<?php echo $v->id; ?>"
data-title="{{ $v->name }}"
href="edit-user/<?php echo $v->id; ?>">
<i class="glyphicon glyphicon-edit" title="Edit" ></i>
Edit
</a>
Js
$('.edit_user_').click(function(e){
e.preventDefault();
var url = $(this).attr('href');
BootstrapDialog.show({
title: $(this).attr('data-title') +"'s "+ 'Information',
message: $('<div></div>').load(url),
closable: true,
closeByBackdrop: false,
closeByKeyboard: false,
draggable: true,
buttons: [{
icon: 'glyphicon glyphicon glyphicon-save',
label: 'Update',
action: function(dialogRef) {
$('form').submit();
},
cssClass: 'btn-primary'
}]
});
return false;
});
Controller
public function updateSelectedUser(Request $request){
$id = $request->input('hId');
$oldImage = $request->input('oldImage');
$validator = $this->validate($request, [
'email' => 'required|email|unique:users,email,'.$id,
'name' => 'required|min:5',
'userimage' => 'required|image'
]);
//$path = Storage::putFile('userimages',$request['userimage']);
if ($validator->fails()) {
return Redirect::back()->with(array('error_code'=>1, 'uId'=>$id));
} else {
echo 'Validation Done';
}
}
And my edit.blade.php template
<div class='row'>
<div class='col-md-12'>
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Edit User</h3>
</div>
<!-- form start -->
<form class="" role="form" method="post" enctype="multipart/form-data" files="true" action="<?php echo asset('regUser/update');?>" >
{{ csrf_field() }}
<input type="hidden" name="hId" value="{{ $info->id }}">
<div class="box-body">
<!-- Name -->
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" >Name</label>
<input id="name" type="text" class="form-control" name="name" value="{{ old('name', $info->name)}}" placeholder="Your Name" required >
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
<!-- Email -->
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" >Email</label>
<input id="email" type="text" class="form-control" name="email" value="{{ old('email', $info->email)}}" placeholder="Your Email" required >
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<!-- Profile Pic-->
<div class="row">
<div class='col-md-6'>
<div class="form-group">
<label for="userimage" >Image</label>
<input id="userimage" type="file" name="userimage" required>
#if ($errors->has('userimage'))
<span class="help-block">
<strong>{{ $errors->first('userimage') }}</strong>
</span>
#endif
</div>
</div>
<div class='col-md-6'>
<div class="form-group">
<label for="userimage" >Old Image</label>
<img class="img-circle" src="{{asset('public/storage/'. $info->userimage )}}" alt="" style="height:50px;"/>
<input type="hidden" name="oldImage" value="{{ $info->userimage }}">
</div>
</div>
</div>
</div>
<!-- /.box-body -->
{!! Form::close() !!}
</div>
</div><!-- /.col -->
</div><!-- /.row -->

Categories