#jquery #ajax #laravel
#jquery #ajax #laravel
Вопрос:
Я пытаюсь отправить форму с помощью jQuery Ajax
. Форма успешно отправляется (через Ajax Submit
), если нет проблем с полями ввода. Однако, если в полях ввода есть проблемы (например, пустые поля), то средство проверки не запускается. Консоль отображает сообщение об ошибке в виде
SQLSTATE[23000]: Integrity constraint violation: 1048......
и контроллер переходит к error:
части ajaxsubmit
, но я хочу, чтобы валидатор сначала отображал сообщения об ошибках в соответствующих полях ввода ( small
используется для отображения ошибок)
Вот мой блейд-код-
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C OGpamoFVy38MVBnE IbbVYUew OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU 6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV rV" crossorigin="anonymous"></script>
<!-- CSRF Token Meta Added -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Ajax script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<!-- Sweet Alert -->
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<!-- JQuery validation Plugin -->
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<!-- <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> -->
<!-- <script src="js/jquery.validate.js"></script> -->
</head>
<body>
<!-- Navigation Bar -->
<div class="container-fluid">
<div class="row">
<div class="col">
<nav class="navbar navbar-expand-sm bg-dark navbar-dark navbar-fixed-top">
<a class="navbar-brand" href="index">User Info</a>
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="home">Home</a>
</li>
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About Us</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Us</a>
</li>
</ul>
@if(isset(Auth::user()->email))
<ul class="nav navbar-nav navbar-right">
<li class="nav-item"><a class="nav-link" href="{{url('logout')}}"> Logout</a></li>
@endif
</ul>
</nav>
</div>
</div>
</div>
@if(isset(Auth::user()->email))
<div class="alert alert-success text-center" role="alert">
<strong> Hello {{Auth::user()->first_name}}!</strong> You are Logged In.
</div>
<div class="alert alert-info text-center" role="alert">
<strong>Edit</strong> your data here<br>
<strong>Note : </strong>You cannot change your password from here. Use <a href="">Reset password</a> instead
</div>
<form class="form-group" id="edit_user_form" method="POST" autocomplete="off">
<div class="row m-5 p-5 bg-success text-white">
<div class="col">
<div class="form-group">
@csrf
<input type="hidden" name="_token" id="csrf" value="{{Session::token()}}">
<input type="hidden" name="id" id="id" value="{{Auth::user()->id}}">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="first_name" name="first_name" value="{{Auth::user()->first_name}}" >
<small class="text-danger bg-white form_error"></small>
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<!-- <input type="text" class="form-control" name="last_name" id="last_name" value="{{Auth::user()->last_name}}"> -->
<input type="text" class="form-control" name="last_name" id="last_name" value="{{Auth::user()->last_name}}" >
<small class="text-danger bg-white form_error"></small>
</div>
<div class="form-group">
<label for="email">Email/Username:</label>
<input type="text" class="form-control" name="email" id="email" value="{{Auth::user()->email}}">
<small class="text-danger bg-white form_error"></small>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="text" class="form-control" name="hpassword" id="hpassword" value="{{'**** For security, your password is hidden****'}}" readonly>
<input type="hidden" class="form-control" name="password" id="password" value="{{Auth::user()->password}}" readonly>
</div>
<div class="form-group">
<label for="mobno">Mobile Number:</label>
<input type="text" class="form-control" name="mobno" id="mobno" value="{{Auth::user()->mobno}}">
<small class="text-danger bg-white form_error"></small>
</div>
<div class="form-group">
<label for="dob">Date of Birth(in YYYY-MM-DD):</label>
<input type="text" class="form-control" name="dob" id="dob" value="{{Auth::user()->DOB}}">
<small class="text-danger bg-white form_error"></small>
</div>
<div class="form-group">
<label for="gender">Gender:</label>
<input type="text" class="form-control" name="gender" id="gender" value="{{Auth::user()->gender}}">
<small class="text-danger bg-white form_error"></small>
</div>
<div class="form-group">
<label for="address">Address:</label>
<textarea class="form-control" rows="5" name="address" id="address">{{Auth::user()->address}}</textarea>
<small class="text-danger bg-white form_error"></small>
</div>
<!-- <div class="form-group">
<label for="country">Country:</label>
<input name="country" class="form-control" id="countrylist" value="{{Auth::user()->country}}">
</div> -->
<div class="form-group {{ $errors->has('country') ? ' has-error' : '' }}">
<label for="country">Country:</label>
<select name="country" class="form-control" id="countrylist">
<option disabled>Select Country</option>
@foreach($countryname as $key => $country)
<option id="countryname" value="{{$country->countryname}}" {{old('country',$country->countryname)== Auth::user()->country ?'selected' :''}}>{{$country->countryname}}</option>
@endforeach
</select>
<small class="text-danger bg-white form_error">{{$errors->first('country') }}</small>
</div>
<div class="form-group">
<label for="dt">Date and Time of Update:</label>
<input type="text" class="form-control" name="dt" id="dt" value=@php date_default_timezone_set("Asia/Kolkata"); echo date("Y-m-d,H:i:s ") @endphp readonly>
</div>
<div class="form-group text-center">
<!-- <a href="{{url('recheck_form')}}"/><button type="submit" class="btn btn-primary mb-2 text-center" onclick="store_using_ajax()">Submit</button> -->
</div>
<div class="form-group text-center ">
<button type="submit" class="btn btn-warning" id="edit_user_button">Edit</button>
<!-- <a href="{{url('dashboard')}}"></a> -->
<button class="btn btn-info" id="cancel_edit">Cancel</button>
</div>
</div>
</div>
</form>
</div>
<!-- Cancel button -->
<script type="text/javascript">
$(document).ready(function(){
$('#cancel_edit').click(function (e){
e.preventDefault();
window.location="dashboard";
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("nowhitespace", function(value, element) {
return this.optional(element) || /^S $/i.test(value);
}, "No white space please");
$("#edit_user_form").validate({
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname:{
required:true,
nowhitespace :true
},
lastname:{
required:true,
nowhitespace :true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true,
nowhitespace :true
},
mobno: {
required:true,
digits:true,
minlength: 10,
maxlength: 10,
nowhitespace :true
},
dob:{
required:true,
date:true,
dateISO: true,
nowhitespace :true
},
gender : {
required:true,
nowhitespace :true
},
address:{
required:true,
nowhitespace :true
},
country:{
required:true,
nowhitespace :true
},
},
// Specify validation error messages
messages: {
firstname: {
required:"Firstname field cannot be empty"
},
lastname: {
required:"Lirstname field cannot be empty"
},
email: {
required: "Email address cannot be blank",
email: "Email format should be example@examle.com or similar"
},
mobno:{
required:"Mobile Number cannot be empty",
digits:"Mobile number must contain only numbers from 0-9",
minlength:"Mobile number must be 10 digits long",
minlength:"Mobile number must be 10 digits long",
},
dob:{
required:"Date of Birth cannot be empty",
date:"The Date input must be a date",
dateISO: "The Date input must be of the form YYYY-MM-DD"
},
gender:{
required:"The gender field cannot be empty",
},
address:{
required:"The address field cannot be empty"
},
country:{
required:"The country field cannot be empty "
},
},
submitHandler: function(form){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}); //Ajaxsetup ends
$.ajax({
type:"POST" ,
url: "validate_loggedin_user_in_database" ,
cache: false,
processData:true, //Required
contentType: 'application/x-www-form-urlencoded',
data: {
'_token' : $("#csrf").val(),
'id' : $('#id').val(),
'first_name' : $('#first_name').val(),
'last_name' : $('#last_name').val(),
'email' : $('#email').val(),
'password' : $('#password').val(),
'mobno' : $('#mobno').val(),
'dob' : $('#dob').val(),
'gender' : $('#gender').val(),
'address' : $('#address').val(),
'country' : $('#countrylist').val(),
},
dataType: 'JSON',
success:function enter_data(response){
swal({
title: "Form Submitted Successfully!",
text: "Data Updated. ",
icon: "success",
button: "Redirecting....",
timer: 5000,
});
setTimeout(function(){ window.location = "dashboard";},5000);
// console.log(response);
},
error: function error_in_submitting(response){
swal({
title: "Error in submitting form",
text: "Please try again later! ",
icon: "warning",
button: "Okay",
});
// console.log(response);
},
}); //Ajax Submit ends
},// submithandler ends
}); //Validate end
});//document ready end
</script>
@endif
<!-- Unauthenticated users are kicked out -->
@if(!isset(Auth::user()->email))
<!-- <a href="{{url('logout')}}"/> <button type="button" class="btn btn-danger btn-lg btn-block">Unauthorised user! Please login or signup before you can enter this page</button> -->
<script type="text/javascript">window.location="login"</script>
@endif
</body>
</html>
И я снова переписываю часть валидатора для удобства
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("nowhitespace", function(value, element) {
return this.optional(element) || /^S $/i.test(value);
}, "No white space please");
$("#edit_user_form").validate({
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname:{
required:true,
nowhitespace :true
},
lastname:{
required:true,
nowhitespace :true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true,
nowhitespace :true
},
mobno: {
required:true,
digits:true,
minlength: 10,
maxlength: 10,
nowhitespace :true
},
dob:{
required:true,
date:true,
dateISO: true,
nowhitespace :true
},
gender : {
required:true,
nowhitespace :true
},
address:{
required:true,
nowhitespace :true
},
country:{
required:true,
nowhitespace :true
},
},
// Specify validation error messages
messages: {
firstname: {
required:"Firstname field cannot be empty"
},
lastname: {
required:"Lirstname field cannot be empty"
},
email: {
required: "Email address cannot be blank",
email: "Email format should be example@examle.com or similar"
},
mobno:{
required:"Mobile Number cannot be empty",
digits:"Mobile number must contain only numbers from 0-9",
minlength:"Mobile number must be 10 digits long",
minlength:"Mobile number must be 10 digits long",
},
dob:{
required:"Date of Birth cannot be empty",
date:"The Date input must be a date",
dateISO: "The Date input must be of the form YYYY-MM-DD"
},
gender:{
required:"The gender field cannot be empty",
},
address:{
required:"The address field cannot be empty"
},
country:{
required:"The country field cannot be empty "
},
},
submitHandler: function(form){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}); //Ajaxsetup ends
$.ajax({
type:"POST" ,
url: "validate_loggedin_user_in_database" ,
cache: false,
processData:true, //Required
contentType: 'application/x-www-form-urlencoded',
data: {
'_token' : $("#csrf").val(),
'id' : $('#id').val(),
'first_name' : $('#first_name').val(),
'last_name' : $('#last_name').val(),
'email' : $('#email').val(),
'password' : $('#password').val(),
'mobno' : $('#mobno').val(),
'dob' : $('#dob').val(),
'gender' : $('#gender').val(),
'address' : $('#address').val(),
'country' : $('#countrylist').val(),
},
dataType: 'JSON',
success:function enter_data(response){
swal({
title: "Form Submitted Successfully!",
text: "Data Updated. ",
icon: "success",
button: "Redirecting....",
timer: 5000,
});
setTimeout(function(){ window.location = "dashboard";},5000);
// console.log(response);
},
error: function error_in_submitting(response){
swal({
title: "Error in submitting form",
text: "Please try again later! ",
icon: "warning",
button: "Okay",
});
// console.log(response);
},
}); //Ajax Submit ends
},// submithandler ends
}); //Validate end
});//document ready end
</script>
Чего я хочу, так это
- ошибки должны появиться под соответствующими полями сразу после того, как пользователь покинет это поле ввода и перейдет к другому
- поля ввода должны светиться красным
Любая помощь, пожалуйста?
Кроме того, как мне проверить, принято ли электронное письмо, и показать пользователю сообщение об ошибке для этого?
Ответ №1:
Вы можете сделать это для достижения ваших требований.
Сначала отправьте свою форму явно, нажав кнопку редактирования, и проверьте там проверку. Замените script
весь ваш код следующим кодом
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("nowhitespace", function(value, element) {
return this.optional(element) || /^S $/i.test(value);
}, "No white space please");
var validator = $("#edit_user_form").validate({
rules: {
firstname:{
required:true,
nowhitespace :true
},
lastname:{
required:true,
nowhitespace :true
},
email: {
required: true,
email: true,
nowhitespace :true
},
mobno:{
required:true,
digits:true,
minlength: 10,
maxlength: 10,
nowhitespace :true
},
dob:{
required:true,
date:true,
dateISO: true,
nowhitespace :true
},
gender:{
required:true,
nowhitespace :true
},
address:{
required:true,
nowhitespace :true
},
country:{
required:true,
nowhitespace :true
},
},
messages: {
firstname: {
required:"Firstname field cannot be empty"
},
lastname: {
required:"Lirstname field cannot be empty"
},
email: {
required: "Email address cannot be blank",
email: "Email format should be example@examle.com or similar"
},
mobno:{
required:"Mobile Number cannot be empty",
digits:"Mobile number must contain only numbers from 0-9",
minlength:"Mobile number must be 10 digits long",
minlength:"Mobile number must be 10 digits long",
},
dob:{
required:"Date of Birth cannot be empty",
date:"The Date input must be a date",
dateISO: "The Date input must be of the form YYYY-MM-DD"
},
gender:{
required:"The gender field cannot be empty",
},
address:{
required:"The address field cannot be empty"
},
country:{
required:"The country field cannot be empty "
},
},
errorPlacement: function (error, element) {
element.each(function () {
$(this).next("div .error").html(error);
});
},
});
// AJAX PART
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click','#edit_user_button',function(e){
e.preventDefault();
if($("#edit_user_form").valid()){
$.ajax({
type:"POST" ,
url: "validate_loggedin_user_in_database" ,
cache: false,
processData:true, //Required
contentType: 'application/x-www-form-urlencoded',
data: {
'_token' : $("#csrf").val(),
'id' : $('#id').val(),
'first_name' : $('#first_name').val(),
'last_name' : $('#last_name').val(),
'email' : $('#email').val(),
'password' : $('#password').val(),
'mobno' : $('#mobno').val(),
'dob' : $('#dob').val(),
'gender' : $('#gender').val(),
'address' : $('#address').val(),
'country' : $('#countrylist').val(),
},
dataType: 'JSON',
success:function enter_data(response){
swal({
title: "Form Submitted Successfully!",
text: "Data Updated. ",
icon: "success",
button: "Redirecting....",
timer: 5000,
});
setTimeout(function(){ window.location = "dashboard";},5000);
},
error: function error_in_submitting(response){
swal({
title: "Error in submitting form",
text: "Please try again later! ",
icon: "warning",
button: "Okay",
});
},
}); //Ajax Submit ends
}
});
});
</script>
И создайте пустой div с классом ошибки перед закрытием каждой входной группы следующим образом
<div class="form-group">
<label for="address">Address:</label>
<textarea class="form-control" rows="5" name="address" id="address">{{Auth::user()->address}}</textarea>
<small class="text-danger bg-white form_error"></small>
<div class="error"></div> // This Line needs to be added in every form-group
</div>
И, наконец, добавьте css, чтобы получить красную рамку для подобных ошибок
.error{
color:red;
}
Дайте мне знать, если у вас возникнут какие-либо проблемы
Комментарии:
1.
error: function error_in_submitting(response){ swal({ title: "Error in submitting form", text: "Please try again later! ", icon: "warning", button: "Okay", }); },
Похоже, что контроллер напрямую переходит к этому, валидатор не запускается2. Я узнал. Это были имена полей. По-видимому, мне пришлось переименовать firstname в first_name
3. кстати, как мне заставить поля ввода светиться красным при наличии ошибок?
4. @Asish просто добавьте этот класс ошибок html в элемент div и добавьте этот css
5. Я этого не понял. Можете ли вы показать мне пример кодирования? Один должен сделать.