Switch between two contents with Jquery html replace - php

I have two popups (login & register) that i want to be able to switch between them with the click event on a span.
It works for the first time but then when i want to switch from the second popup to first one, the click event doesnt trigger meaning i cant go to the first popup after i went to second.
I searched and i discovered that the click events attached to elements are lost, but still couldnt achieve a solution.
- How can i switch between the two as many times as i want on the span click event (registerform and loginform classes) ?
HTML:
<div id="myModal" class="modal">
#include('frontoffice.login_popup')
</div>
The first time it loads with login view:
<div class="modal-content">
<span class="close">×</span>
<div class="popup-form">
<div class="popup_title">
OLÁ DE NOVO, LUZINHA !
</div>
<p class="popupcontent"> Se ainda não pertences á familia wolistic, <br> regista-te <span class="registerform orange"> aqui </span> </p>
{{ Form::open(array('method'=>'post','class'=> 'popup_form', 'url'=>'/customer_login')) }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<input id="email" type="email" class="form-control popupinput" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<input id="password" type="password" class="form-control popupinput" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
<div class="form-group popsubmit">
<button type="submit" class="btn btn-primary">INICIAR SESSÃO</button>
</div>
<p class="text_forgotpassword"> Esqueceste a password? Nós ajudamos, clica <span class="orange"> aqui! </span> </p>
{{Form::close()}}
</div>
</div>
Register view:
<!-- Modal content -->
<div class="modal-content" style="height: 65%">
<span class="close">×</span>
<div class="popup-form">
<div class="popup_title">
JUNTA-TE À FAMILIA WOLISTIC
</div>
<p class="popupcontent"> Já fazes parte ? Conecta-te <span class="loginform orange"> aqui </span> </p>
{{ Form::open(array('method'=>'post','class'=> 'popup_form', 'url'=>'/customer_register')) }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<input id="name" type="text" class="form-control popupinput" placeholder="Nome" name="name" value="{{ old('name') }}" required autofocus>
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<input id="email" type="email" class="form-control popupinput" placeholder="E-mail" name="email" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<input id="password" type="password" class="form-control popupinput" placeholder="Password" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
<div class="form-group">
<input id="password-confirm" type="password" class="form-control popupinput" placeholder="Repetir Password" name="password_confirmation" required>
</div>
<div class="form-group">
<div class="interests_list register_list">
<div>
<input type="checkbox" id="agree" name="agree"/>
<label for="agree"><span></span> Li e concordo com os termos e condições </label>
</div>
<div>
<input type="checkbox" id="sub" name="sub"/>
<label for="sub"><span></span> Quero subscrever a newsletter </label>
</div>
</div>
</div>
<div class="form-group popsubmit">
<button type="submit" class="btn btn-primary">REGISTAR</button>
</div>
{{ Form::close() }}
</div>
</div>
</div>
JS:
$(".registerform").click(function(){
$.get(
"/registerform",
function (data) {
$("#myModal").html(data);
}
);
});
$(".loginform").click(function(){
$.get(
"/loginform",
function (data) {
$("#myModal").html(data);
}
);
});
Trigger the modal:
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("openloginpopup");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}

I think this can help you, if you press the "open" button swtich between modals if one of them are open, if not open the modal1:
HTML
<div id="openloginpopup">
<div class="modal-content">
open
</div>
</div>
<div id="myModal" class="modal">
<div class="modal-content modal1">
<span class="close">×</span>
<div class="popup-form">
modal1
</div>
</div>
</div>
<div id="myModal2" class="modal">
<div class="modal-content modal1">
<span class="close">×</span>
<div class="popup-form">
modal2
</div>
</div>
</div>
JS
$("#openloginpopup").on('click', function(){
if(!$('#myModal').is(':visible') && !$('#myModal2').is(':visible')){
$('#myModal').modal('show');
}else{
if($('#myModal').is(':visible')){
$('#myModal2').modal('show');
$('#myModal').modal('hide');
}else{
$('#myModal2').modal('hide');
$('#myModal').modal('show');
}
}
});
$(".modal").on('click', function(){
$(this).modal('hide');
});
Test link
https://jsfiddle.net/022bca5x/12/

You seem to be using Bootstrap so there is no need to use vanilla JS to control the modal and even more so when you're already using jQuery.
As per Bootstrap docs, you can use
$('#myModal').modal('show'); // show the modal
$('#myModal').modal('hide'); // hide the modal
Try
$("#openloginpopup").on('click', function(){
$('#myModal').modal('show');
}
In order to open another modal from within your current modal, first hide the active one, then open the second and vice versa.
$("#SECOND_MODAL_BUTTON").on('click', function(){
$('#FIRST_MODAL').modal('hide');
$('#SECOND_MODAL').modal('show');
}
$("#FIRST_MODAL_BUTTON").on('click', function(){
$('#SECOND_MODAL').modal('hide');
$('#FIRST_MODAL').modal('show');
}

Related

Modal Uncaught TypeError: Illegal invocation

I'm developing a laravel project. After logging in with modal, I tried to register with modal, but I encountered an error. I'm waiting for your help. I WILL SHARE THE SEAMLESS PART AT THE BOTTOM
I don't know why this is so. I have no problem with login. However, I am having a problem with the registration part. I did some research on modal but couldn't solve the problem
Error:
register modal
<div class="modal fade" id="modal--register-kayit" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-contentt">
<!-- <div class="modal-header">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div> -->
<body class="login">
<section class="login">
<div class="container-login">
<div class="form-login">
<button type="button" class="btn-closee" data-bs-dismiss="modal" aria-label="Close"></button>
<h2 class="login" >
<a href="{{ url('/') }}" style="text-decoration:none; margin-left: 50px;">
{{ $site_name }}
</a>
</h2>
<form class="form-login" action="{{ route('register) }}" method="post">
{{ csrf_field() }}
<div>
<div class="inputBx">
<input id="name" type="text" class="login #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" required autocomplete="name">
<span class="login">{{ __('Kullanıcı Adı') }}</span>
#if($errors->has('name'))
<script>
$(document).ready(function() {
$('#modal--register--kayit').modal('show');
});
</script>
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
<i class="fas fa-user-circle"></i>
</div>
<div class="inputBx">
<input id="email" type="email" class="login #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
<span class="login">{{ __('Email') }}</span>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<i class="fas fa-envelope"></i>
</div>
<div class="inputBx password">
<input id="password" type="password" class="login #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
<i class="fas fa-key"></i>
<span class="login">Şifre</span>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="inputBx password">
<input id="password-confirm" type="password" class="login" name="password_confirmation" required autocomplete="off">
<i class="fas fa-key"></i>
<span class="login">{{ __('auth.confirm_password') }}</span>
</div>
<form action="#" onsubmit="
if(document.getElementById('agree').checked) {
return true;
} else {
alert('Lütfen Şartlar ile Gizlilik Politikasını okuyup kabul ettiğinizi belirtin.'); return false; }">
<input class="login" type="checkbox" required name="checkbox" value="check" id="agree" /> Okudum ve onaylıyorum <br> Şartlar ve Politikalar
</form>
<!--
<div class="mb-3">
<label class="form-check">
<input type="checkbox" class="form-check-input">
<span class="form-check-label">Agree the .</span>
</label>
</div>
-->
{!! NoCaptcha::display() !!}
<span class="" role="alert">
<strong style="color: red;">#error('g-recaptcha-response') {{ $message}} #enderror</strong>
</span>
<div class="inputBx">
<input type="submit" value="{{ __('Yeni Hesap Oluştur') }}" class="login" style="max-width: 180px;">
</div>
</form>
#if (Route::has('password.request'))
<p class="login">Şifreni mi Unuttun?
<a class="login" href="{{ route('password.request') }}">
Sıfırlamak için tıkla!
</a>
</p>
#endif
<p class="login">Henüz bir hesabınız yok mu? <a class="login" href="{{ url('register') }}">Kayıt Ol</a></p>
</div>
</div>
</section>
</body>
</div>
</div>
</div>
Where I call Modal
<a href="#" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal--register--kayit">
{{ __('auth.register') }}
</a>
SEAMLESS ENTRY MODAL
<div class="modal fade" id="modal--login--giris" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-contentt">
<!-- <div class="modal-header">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div> -->
<body class="login">
<section class="login">
<div class="container-login">
<div class="form-login">
<button type="button" class="btn-closee" data-bs-dismiss="modal" aria-label="Close"></button>
<h2 class="login" >
<a href="{{ url('/') }}" style="text-decoration:none; margin-left: 50px;">
{{ $site_name }}
</a>
</h2>
<form method="POST" action="{{ route('login') }}" class="form-login">
{{ csrf_field() }}
<div class="inputBx">
<input id="email" type="email" class="login #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
<span class="login">{{ __('Kullanıcı Adı') }}</span>
#error('email')
<script>
$(document).ready(function() {
$('#modal--login--giris').modal('show');
});
</script>
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<i class="fas fa-user-circle"></i>
</div>
<div class="inputBx password">
<input id="password" type="password" class="login #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
<p href="#" class="password-control login" onclick="return show_hide_password(this);"> </p>
<i class="fas fa-key"></i>
<span class="login">Şifre</span>
#error('password')
<script>
$(document).ready(function() {
$('#modal--login--giris').modal('show');
});
</script>
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<label class="remember">
<input type="checkbox" class="login form-check-input remember" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}> {{ __('Beni Hatırla') }}
</label>
{!! NoCaptcha::display() !!}
#error('g-recaptcha-response')
<script>
$(document).ready(function() {
$('#modal--login--giris').modal('show');
});
</script>
<span class="" role="alert">
<strong style="color: red;">Lütfen Robot Olmadığınızı Kanıtlayın.</strong>
</span>
#enderror
<div class="inputBx">
<!-- <button type="submit" name="submit" value="Log in">{{ __('Giriş Yap') }}</button>-->
<input type="submit" value="{{ __('Giriş Yap') }}" class="login">
</div>
</form>
#if (Route::has('password.request'))
<p class="login">Şifreni mi Unuttun?
<a class="login" href="{{ route('password.request') }}">
Sıfırlamak için tıkla!
</a>
</p>
#endif
<p class="login">Henüz bir hesabınız yok mu? Kayıt Ol</p>
</div>
</div>
</section>
</body>
</div>
</div>
</div>

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.

How to send login errors back without any redirect ? Laravel 5.4

In the Laravel code: AuthenticatesUsers.php there's this function that returns error messages back to the user, for example if they didn't enter a registered email address:
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
My issue is that I'm using a Modal box so when this function redirects to the same page the modal disappears and the user can only see the errors when he clicks to see the modal again.
How can I send the data back without using redirect() or any refresh ?
This is the AJAX call I'm using:
<script type="text/javascript">
$(function(){
$('#login').click(function(e) {
e.preventDefault();
$('#myModal').modal();
});
$(document).on('submit', '#formLogin', function(e) {
e.preventDefault();
$.ajax({
method: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: "json"
})
.done(function(data) {
console.log(data);
})
.fail(function(data) {
console.log(data);
});
});
})
</script>
For completion, this is the entire Modal with both the registration and login forms:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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">recharge.ae | Welcome!</h4>
</div>
<div class="modal-body">
<div id="reg-div">
<h4>New customer? Register below.</h4>
<form class="form-horizontal" method="POST" action="{{ route('register') }}" id="formRegister">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>
{{-- <small class="help-block"></small> --}}
#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-reg" type="email" class="form-control" name="email" value="{{ old('email') }}" required>
{{-- <small class="help-block"></small> --}}
#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' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
{{-- <small class="help-block"></small> --}}
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register and Log Me In
</button>
</div>
</div>
</form>
</div><!--#reg-div-->
<div id="login-div">
<h4>Returning customer? Login below.</h4>
<form class="form-horizontal" method="POST" action="{{ route('login') }}" id="loginForm">
{{ csrf_field() }}
<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 autofocus>
#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' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div><!-- #login-div -->
</div>
</div>
</div>
</div>
Well, return a JSON response rather than redirecting the page. Here's how to do it. Rather than this
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
write this
return json_encode([ 'errorr' => $$errors ]);
and via above line, you get the data in the done function of the ajax. There you just need to parse that JSON like this
data = JSON.parse(data);
and then you can access the errors like this data.errors but here you need to keep one thing in mind you will need to attach these errors in the html yourself
P.S If there is anything that you don't understand feel free to ask

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