Работа над многоступенчатой формой, которая имеет 3 фазы.На этапе 1 пользователь заполняет форму, которая передается бэкэнду для проверки, некоторого вычисления данных, а затем передается на второй этап, где пользователь запускает кнопку с динамическим идентификатором.Затем я использую AJAX для извлечения значений, введенных пользователем в 1-й фазе формы, и уникального идентификатора кнопки, которую пользователь нажал во 2-й фазе, в конечный контроллер.
Проблема в AJAXНе пытайтесь выбрать значения из 1-й фазы формы, когда я пытаюсь использовать dd ($ quote) , как показано в приведенном ниже коде.
Этап 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>
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-код для извлечения значений при нажатии кнопки на 2-й фазе
$('.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
Конечный контроллер для использования значений, выбранных через запрос AJAX выше
//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);
}