Display error message in modal, after validation error in laravel - javascript

I have a problem displaying errors message in update modal form. I'm using laravel request for validation and AJAX to submit form inside a modal. I would like to see the error message for each field that are inputted incorrectly. However, I'm getting this error:
The Given data is invalid
I checked the network tab, and I'm seeing the errors there but I can't figure out why this is not showing in my fields.
Here is my script's
function updatePassword(e, t)
{
e.preventDefault();
const url = BASE_URL + '/admin/organizations/operators/updatePassword/' + $(updatePasswordForm).find("input[name='id']").val();
var form_data = $(t).serialize();
// loading('show');
axios.post(url, form_data)
.then(response => {
notify(response.data.message, 'success');
$(updatePasswordModal).modal('hide');
// roleTable.ajax.reload()
})
.catch(error => {
const response = error.response;
if (response) {
if (response.status === 422)
validationForm(updatePasswordForm, response.data.errors);
else if(response.status === 404)
notify('Not found', 'error');
else
notify(response.data.message, 'error');
}
})
.finally(() => {
// loading('hide');
});
}
Here is my Blade file
<form id="updatePasswordForm" onsubmit="updatePassword(event, this)">
<input type="hidden" name="id" value="">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> {{ __('Update Password') }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-sm-4 col-form-label required">{{ __('New Password') }}</label>
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password') error #enderror">
<input type="password" class="form-control" id="password" name="user[password]" placeholder="{{ __('Password') }}" required>
</div>
</div>
</div>
#error('user.password')
<p class="error-message">{{ $message }}</p>
#enderror
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label required">{{ __('Confirm Password') }}</label>
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
</div>
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-secondary mr-3" data-dismiss="modal">{{ __('Close') }}</button>
<button type="submit" class="btn btn-primary">{{ __('Save') }} </button>
</div>
</div>
</form>
Here is My Controller:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Organization\Operator\UpdatePasswordRequest;
use App\Models\OrganizationOperator;
use Illuminate\Http\Request;
use App\Services\Response;
use Exception;
use Illuminate\Support\Facades\Log;
class OrganizationController extends Controller
{
public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
{
try {
$data = $request->validated();
$user = $data['user'];
// dd($user['password']);
$operator->update([
'password' => bcrypt($user['password']),
]);
return Response::success(__('Successfully updated'));
} catch (Exception $e) {
Log::error($e->getMessage());
return Response::error(__('Unable to update'), [], 500);
}
}
}
Here is my Request Validation Class:
<?php
namespace App\Http\Requests\Admin\Organization\Operator;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePasswordRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'id' => ['required', 'integer', 'exists:organization_operators,id'],
'user.password' => ['required', 'string', 'min:8', 'confirmed'],
];
}
}

First, I think this issue is because you send the request from the client side (which is is ajax/axios). The validation work when you submit to the server side (without ajax/axios) then response validation will display to the blade/html.
In this case, you must set error to the html manually (with innerHTML or .html() in jquery) using class/id.
for example this response from the server/api :
{ "error" : {
"user.password" : ["invalid password"],
...
}
}
in client side, you need to put that message to html tag in that case with p tag.
<p id="error-password" ></p>
$('#error-password').html(error["user.password"])
// or
$('#error-password').text(error["user.password"])

Finally I solved this problem.
1. I change my controller
public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
TO
public function updateOperatorPasswordApi(User $user, UpdatePasswordRequest $request)
AND
try {
$data = $request->validated();
$user = $data['user'];
// dd($user['password']);
$operator->update([
'password' => bcrypt($user['password']),
]);
return Response::success(__('Successfully updated'));
}
TO
try {
$data = $request->validated();
$user->update([
'password' => bcrypt($data['password']),
]);
return Response::success(__('Successfully created'));
}
2. I change my blade file
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
TO
<div class="form-group">
<label for="">{{ __('Password') }}</label>
<input name="password" type="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="{{ __('Password') }}" required>
<small class="form-text error-message"></small>
</div>
AND
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
TO
<div class="form-group">
<label for="">{{ __('Confirm Password') }}</label>
<input name="password_confirmation" type="password" class="form-control" id="password_confirmation" aria-describedby="emailHelp" placeholder="{{ __('Confirm Password') }}" required>
<small class="form-text error-message"></small>
</div>

Related

Modal Validation with Javascript in laravel form

My code uses a modal for form display, and I want to make the modal unlock when validation is active.
but after i add some javascript function line, it still doesn't work.
My Modal
<div class="modal fade" id="passwordModal{{Auth::user()->id}}">
<div class="modal-dialog modal-lg-6">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="passwordModal">Update Password</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{ route('password.update') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="content">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input name="current_password" type="password" id="current_password" placeholder="Curent Password" class="form-control #error('current_password') is-invalid #enderror">
<span class="text-danger" id="current_passwordError"></span>
<div class="invalid-feedback">
#error('current_password')
{{ $message }}
#enderror
</div>
</div>
<div class="form-group">
<input name="password" id="password" type="password" placeholder="New Password" class="form-control #error('password') is-invalid #enderror">
<span class="text-danger" id="passwordError"></span>
<div class="invalid-feedback">
#error('password')
{{ $message }}
#enderror
</div>
</div>
<div class="form-group">
<input name="password_confirmation" type="password" id="password_confirmation" placeholder="Confirm New Password" class="form-control #error('password_confirmation') is-invalid #enderror">
<span class="text-danger" id="password_confirmationError"></span>
<div class="invalid-feedback">
#error('password_confirmation')
{{ $message }}
#enderror
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
and my function js
<script>
function openModal() {
$('#passwordModal{{Auth::user()->id}}').modal('show')
}
function storeData() {
var CSRF_TOKEN = $('meta[name="csrf - token"]').sttr('content');
var current_password = $('#current_password').val();
var password = $('#password').val();
var password_confirmation = $('#password_confirmation').val();
$('#current_passwordError').addClass('d-none');
$('#passwordError').addClass('d-none');
$('#password_confirmationError').addClass('d-none');
$.ajax({
type: 'POST',
url: "{{ route('password.update') }}",
data: {
_token: CSRF_TOKEN,
current_password: current_password,
password: password,
password_confirmation: password_confirmation,
},
success: function(data) {
},
error: function(data) {
var errors = data.responseJSON;
if ($.isEmptyObject(errors) == false) {
$.each(errors.errors, function(key, value) {
var ErrorID = '#' + key + 'Error';
$(ErrorID).removeClass("d-none");
$(ErrorID).text(value)
})
}
}
});
}
is my script correct, or is there another way that is more effective.
before I could use ?
is my script correct, or is there another way that is more effective.
before i was able to handle this case in ci-3, but when i used that code in laravel it didn't work, that's why i tried another way and this is the result.

Unable to post record using vue and laravel backend

When i try to submit a record to my SQL from vue component with laravel API nothing happens. I have compared my code to other working code but nothing seem to work.
Here is my register method:
register() {
axios
.post('/api/register', this.user)
.then(res => {
console.log(user)
})
.catch(err => {
console.log(err.message)
})
},
Here is the register form:
<template>
<form>
<div class="form-group">
<input
type="text"
v-model="user.name"
name="username"
class="form-control"
id="name"
placeholder="Email or username"
/>
<div class="validation"></div>
</div>
<div class="form-group">
<input
v-model="user.email"
type="email"
class="form-control"
name="email"
id="password"
placeholder="Your Email"
/>
<div class="validation"></div>
</div>
<div class="form-group">
<input
v-model="user.password"
type="password"
class="form-control"
name="password"
placeholder="Your Password"
data-rule="password"
/>
<div class="validation"></div>
</div>
<div id="errormessage"></div>
<div class="text-center">
<button type="submit" title="Register" v-on:click="register">Login</button>
</div>
</form>
</template>
My laravel page:
<section id="pricing" class="wow fadeInUp section-bg">
<div class="container">
<header class="section-header">
<h3>Register</h3>
<p>Come prepared!!</p>
</header>
<div class="row flex-items-xs-middle flex-items-xs-center">
<div class="col-xs-12 col-lg-6">
<div class="card">
<div class="card-header">
<div id="app">
<register></register>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
Here is my controller:
if ($v->fails())
{
return response()->json([
'status' => 'error',
'errors' => $v->errors()
], 422);
}
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['status' => 'success'], 200);
}
The record should post successfully, however nothing happens. I only see the parameters on my url like so, and I don't get any error on console.
You'll need to prevent the default form submission behavior first, then trigger your own register method.
<form #submit.prevent="register">

Javascript fail to redirect after firebase authentication

I'm authenticating users registered in my firebase database and i want to redirect the user after successful authentication
const txtEmail = document.getElementById('email');
const txtPass = document.getElementById('password');
const loginBtn= document.getElementById('reg');
loginBtn.addEventListener('click', e => {
const mail = txtEmail.value;
const pass = txtPass.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(mail, pass);
if(promise){
window.location = "{{ route('users') }}";
console.log("{{ route('users') }}");
}else{
}
});
the log is successfully printed but the redirection fails may someone help
this is my form i don't know but maybe there is something wrong in it
<form class="form-horizontal m-t-20" method="post">
{{ csrf_field() }}
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" type="text" required="" id="email" placeholder="email">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" id="password" required="" name="password" placeholder="Password">
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<div class="checkbox checkbox-custom">
<input id="checkbox-signup" type="checkbox">
<label for="checkbox-signup">
Remember me
</label>
</div>
</div>
</div>
<div class="form-group text-center m-t-30">
<div class="col-xs-12">
<button class="btn btn-custom btn-bordred btn-block waves-effect waves-light" class="reg" id="reg">
Login
</button>
</div>
</div>
<div class="form-group m-t-30 m-b-0">
<div class="col-sm-12">
<i class="fa fa-lock m-r-5"></i> Forgot your password?
</div>
</div>
</form>

How to upload text along with image using ajax

I was trying to create a signup form where a user has to give his data along with the image. I have attached the snippet of the code I was trying but couldn't achieve please help me. I have already been through other similar question but none of them helped me.
function submitForm1()
{
var data = $("#signup").serialize();
$.ajax({
type : 'POST',
url : 'signup_process.php',
data : data,
async: false,
beforeSend: function()
{
$("#error1").fadeOut();
$("#btn-signup").html('<span class="glyphicon glyphicon-transfer"></span> Signing Up..Please wait.');
},
success : function(response)
{
if(response=="ok"){
$("#error1").fadeIn(1000, function(){
$("#error1").html('<div class="alert alert-success"> <span class="glyphicon glyphicon-info-sign"></span> An Email has been sent to your entered email address. Please follow the instruction to activate your account.</div>');
$("#btn-signup").html('<span class="glyphicon glyphicon-transfer"></span> Sign Up');
});
}
else{
$("#error1").fadeIn(1000, function(){
$("#error1").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
$("#btn-signup").html('<span class="glyphicon glyphicon-log-in"></span> Sign In');
});
}
}
cache: false,
contentType: false, //must, tell jQuery not to process the data
processData: false,
});
return false;
}
/* login submit */
});
<div class="container">
<div class="signup-form-container">
<form id="signup" name="form1">
<div class="head"></div>
<div class="form-header" style="text-align:center;">
<div class="image" id="preview">
<div id="timelineShade" style="background:url(assets/pic.png) center;"></div>
</div>
<h3 class="form-title" style="margin-top:-60px;"><span style="margin-right:50px;"></span>Recruiter Sign-up Portal</h3>
</div>
<div class="form-body">
<!-- json response will be here -->
<div id="error1"></div>
<!-- json response will be here -->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
<input type="text" name="name" class="form-control" placeholder="Full Name" id="name" /> </div>
<span class="help-block" id="error"></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></div>
<input type="text" name="email" class="form-control" placeholder="Email" id="email" /> </div>
<span class="help-block" id="error"></span>
</div>
<div class="row">
<div class="form-group col-lg-6">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input type="password" name="password" id="password" class="form-control"placeholder="Password" /> </div>
<span class="help-block" id="error"></span>
</div>
<div class="form-group col-lg-6">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input type="password" name="cpassword" class="form-control" placeholder="Confirm Password"/> </div>
<span class="help-block" id="error"></span>
</div>
</div>
<div class="form-group col-lg-6" style="max-width:145px; margin-top:10px;">
<div class="input-group">
<label>Company Logo</label>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input id="imagein" name="image" type="file" class="form-control" limit=1/>
</div>
<span class="help-block" id="error"></span>
</div>
</div>
<div class="form-footer">
<button type="submit" name="btn-signup" id="btn-signup" class="btn bt-login" style="margin-left:8%; width:92%" >Sign-up <span class="glyphicon glyphicon-log-in"></span> </button>
</div>
<div class="form-footer"> <div class="col-xs-4 col-sm-4 col-md-4" style="margin-left:0%; float:left;">
<i class="fa fa-lock"></i>
Forgot password? </div>
<div class="col-xs-4 col-sm-4 col-md-4" style="margin-left:0%; float:right;">
<i class="fa fa-user"></i>
Log-In </div>
</div>
</form>
</div>
</div>
<?php
session_start();
$upload_dir = '/upload/'; // upload directory
error_reporting(0);
require_once 'class.user.php';
$reg_user = new USER();
if($reg_user->is_logged_in()!="")
{$reg_user->redirect('home.php');}if(isset($_POST['btn-signup'])){
$phone = trim($_POST['phone']);$email = trim($_POST['email']);
$upass = trim($_POST['password']);$code = md5(uniqid(rand()));
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif');
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions)){if($imgSize < 5000000){
move_uploaded_file($tmp_dir,$upload_dir.$userpic);}else{
$errMSG = "Sorry, your file is too large.";}}else{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";}
if($reg_user->register($phone,$email,$upass,$code,$userpic)){
$id = $reg_user->lasdID();$key = base64_encode($id);$id = $key;
$message = "Hello $email,<br /><br />
Welcome to Coding Cage!To complete your registration please , just
clickfollowing link<br/><br /><br /><a href='http://localhost/x/verify.php?
id=$id&code=$code'>Click HERE to Activate :)</a><br /><br />Thanks,";
$subject = "Confirm Registration";require_once('mailer/class.phpmailer.php');
$mail = new PHPMailer();$mail->IsSMTP(); $mail->SMTPDebug = 0;
$mail->SMTPAuth = true; $mail->SMTPSecure = "ssl";
$mail->Host= "smtp.gmail.com"; $mail->Port= 465;
$mail->AddAddress($email);
$mail->Username="sharma.himanshu0405#gmail.com";
$mail->Password="mypassword";
$mail->SetFrom('sharma.himanshu0405#gmail.com','Himanshu');
$mail->Subject = $subject;
$mail->Subject = $subject; $mail->MsgHTML($message);
if($mail->send()) { echo "ok" ; } else {
echo "Sorry, Registration is not possible this time. Please try again after some time or Contact Admin";
$stmt = $reg_user->runQuery("DELETE FROM tbl_users WHERE user_email=:email_id");
$stmt->execute(array(":email_id"=>$email));
}
}
}
?>
Have to encode the image in the form to base64 (not sure) before providing serialized form data in ajax call

Cannot /Post - Login Authentication

I am creating an app and I need a SignIn / SignUp functionality for the same. Here is my SignIn HTML:
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<form action="verifySignin" method="post" id="verifySignin" class="form-horizontal" role="form">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" name="username" value="" placeholder="username" required="" autofocus="" >
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="password" class="form-control" name="password" placeholder="password">
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<button class="btn btn-md btn-primary btn-block" type="submit">Login</button>
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div style="border-top: 1px solid#888; padding-top:15px; font-size:85%" > Don't have an account?
<a href="#" onClick="$('#loginbox').hide(); $('#signupbox').show()">
Sign Up Here
</a>
</div>
</div>
</div>
</form>
</div>
My app.js has the following to route:
app.post('/verifySignin', home.verifySignin);
app.get('/verifySignin', home.verifySignin);
Under routes folder> I have created a home.js file which contains the following:
function verifySignin(req,res)
{
req.session.name=req.param("username");
var password = req.param("password");
console.log("session name:"+req.session.name);
var verifyUserQuery="select username, password from Users where Username='"+req.param("username")+"' and Password = '"+req.param("password")+"'";
mysql.fetchData(function(err,results){
if(err){
throw err;
}
else
{
if(results.username==req.param("username") && results.password == password){
res.render('kanban', { name: req.param("username") });}
else {
res.render('ErrorPage');
}
}
},verifyUserQuery);
}
exports.verifySignin=verifySignin;
When I click on the Login button, I get the error : Cannot POST /verifySignin.
Any help would really be appreciated. Thanks.
Try to use it like,
var users = require('./home/users');
in addition, this is a very bad practice due to security concerns
"select username, password from Users where Username='"+req.param("username")+"' and Password = '"+req.param("password")+"'"
pass values as parameters or bind them.

Categories