I'm sorry if this is a duplicate (i searched everywhere for a possible solution) but i just have to know how to use a jquery code after submitting a form in Laravel.
FYI: I am using Laravel and i use a Redirect::back() when form credentials are correct.
Here's my Controller code used when submitting form:
public function store()
{
$user = array(
'voornaam' => Input::get('voornaam'),
'achternaam' => Input::get('achternaam'),
'email' => Input::get('email'),
'telefoonnummer' => Input::get('telefoonnummer'),
'bedrijfsnaam' => Input::get('bedrijfsnaam'),
'adres' => Input::get('adres'),
'opmerking' => Input::get('opmerking'),
'titel' => Input::get('paginanaam'),
'datum' => Input::get('dedatum'),
'personen' => Input::get('personen'),
);
$data = $user;
$rules = array(
'voornaam' => 'required',
'achternaam' => 'required',
'email' => 'required',
'adres' => 'required',
'bedrijfsnaam' => 'required',
'datum' => 'required',
);
$messages = array(
'voornaam.required' => 'Vul a.u.b. uw voornaam in.',
'achternaam.required' => 'Vul a.u.b. uw achternaam in.',
'email.required' => 'Vul a.u.b. uw emailadres in.',
'adres.required' => 'Vul a.u.b. uw factuuradres in.',
'bedrijfsnaam.required' => 'Vul a.u.b. uw bedrijfsnaam in.',
'datum.required' => 'Selecteer a.u.b. een datum.',
);
if(Input::get('spamcheck'))
{
return 'Stop spamming please.';
}
$validation = Validator::make($data, $rules, $messages);
if ( $validation->fails() )
{
return Redirect::back()->withErrors($validation)->withInput();
} else {
if(Input::get('kopie') === 'ja') {
Mail::send();
} else {
Mail::sendothermail();
}
return Redirect::back();
}
}
I deleted some unneccesary code from this controller (fyi) so you won't get distracted from my problem. When a user submits the form and it has errors, the errors are displayed at the top of the page. But, i would like to make something like: when a user submits the form, and credentials are ok, it reloads the page and should scroll to the form and hides the form and displays a success message instead of the form.
IF this is a duplicate for a similair problem, please let me know.
Upon successful validation return to your view with session flash data to perform if success load js
Controller
return Redirect::back()->with('success');
View - demo
#if(Session::get('success'))
<script>
$('html, body').animate({
scrollTop: $("#form").offset().top
}, 2000);
window.setTimeout(function(){
$('#form').hide().next('#success').show();
}, 1500);
</script>
#endif
Give the element that contains either the form+error or the succes message a 'name' attribute, say 'form'. Then, don't use Redirect:back(), but instead Redirect to the page with #form behind it, for example 'index.php#form'.
JavaScript would offer some more options.
Related
So what i want is to put 'g-recaptcha-response' in a variable to be able to use it in my condition to verify recaptcha but I haven't been able to do this. Is there any way to only use recaptcha field from the array inside validate() because my code as it is, redirects me back to homepage. It goes straight to else statement.
public function contactanospost(Request $request){
$request->validate([
'nombre' => 'required|distinct',
'telefono'=> 'required|telefono',
'correo' => 'required|email',
'mensaje' => 'required',
'g-recaptcha-response' => 'required|captcha',
]);
if(POST['g-recaptcha-response']){ /*here I am trying to
check with a condition if recaptch was really validated once the form is submitted */
$token= POST['g-recaptcha-response'];
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
'form_params' => array('secret' => 'mycaptchakey',
'response'=> $token /*Checking with google parameters for recaptcha if the user was indeed verified */
)
]);
$resultados = json_decode($response->getBody()->getContents()); //decode with json
if($resultados->success){ /*if this was a success then return a page with parameters from google recaptcha such as: secret, response, remote ip.*/
dd($resultados); /*show the results from verified user and that recaptcha is working*/
$contactanos = Contactanos::create($request->all());/* and create all fields for model Contactanos*/
Mail::to('some#mail')->send(new enviacorreo($contactanos)); /* since it is a contact form then send all the information to some mail*/
\Session::flash('flash_message','Tu mensaje ha sido enviado!'); /* send a message with "email delivered" verification*/
return redirect()->back();
}
else{
\Session::flash('flash_message','Robot');
return redirect('/');
}
}
else{
return redirect('/');
}
}
I'm now able to access request properties using input() what got me confused were my if statements. The real problem is that after:
$resultados = json_decode($response->getBody()->getContents());
next if statement is not getting the expected success but instead it goes straight to else with robot message:
else{
\Session::flash('flash_message','Robot');
return redirect('/');
}
You can access all the properties of the request from the $request object by calling e.g, $request->input('g-recaptcha-response') This is the basic of Accessing the request if you have read through the documentation.
I can lend you a snippet to do this perhaps it will help you rethink how you're validating the captcha:
use GuzzleHttp\Client;
....
$v = Validator::make($request->all(), [
'name' => 'required|min:2',
'email' => 'required|email|max:255',
'subject' => 'sometimes|required|min:3',
'message' => 'required|min:3',
'g-recaptcha-response' => 'sometimes|required'
], [
'g-recaptcha-response.*' => 'Please verify that you are not a robot'
]);
if ($v->fails()) {
return [
'success' => 'no',
'data' => $v->errors()->first()
];
}
if ($request->get('g-recaptcha-response')) {
$verify_form = [
'secret' => env('GOOGLE_RECAPTCHA_SECRET', 'default'), //better to save in config though
'response' => $request->get('g-recaptcha-response')
];
$client = new Client();
$verify_serial = '?'.http_build_query($verify_form);
$response = $client->post('https://www.google.com/recaptcha/api/siteverify'.$verify_serial);
$arrayed_response = json_decode($response->getBody()->getContents(), true);
if(!$arrayed_response['success']){
Log::notice('There is something wrong with the verification of recaptcha: ',$arrayed_response );
return [
'success' => 'no',
'data' => 'Something went wrong in verification process',
];
}
}
The idea is that, you build the secret and response body and use that to request validation check from Google just as you have done but building the query as query parameters directly to the url.
PS: you don't have to return the snippet :)
I make many projects with Laravel 5.6 with the same login setup (Use Auth facade), but with one shared hosting the users can't log in. When you enter the correctly mail and password, only reload de login page WITHOUT ANY ERRORS, when in my controller all the views return errors or a message.
This is the code of my login (Works in all servers except in this):
public function login(Request $request) {
$rules = array(
'email' => 'required|email|min:3|max:88',
'password' => 'required|min:3|max:88',
);
$messages = [
'required' => 'El :attribute es requerido',
'email' => 'Tiene que ingresar un mail válido',
'min' => 'Longitud del campo :attribute no válido',
'max' => 'Longitud del campo :attribute no válido',
];
$validator = Validator::make($request->all(), $rules, $messages);
if($validator->fails()) {
return redirect()->intended('admin')->withErrors($validator);
} else {
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
return redirect()->intended('admin');
} else {
return redirect()->intended('admin')->withErrors(['loginFail' => 'Usuario/Contraseña incorrectos']);
}
}
}
If I enter a wrong email or password in any server, this return me to the login view with the errors, but in these the errors don't appear and I can't login with the correct email and password.
I call to the hosting and say me that is nothing wrong, how can i solve it?
I get the wrong error messages. My purpose is following :
1. checking username / pw combination, and if it doesn't match, "wrong username/pw combination" error through validator.
2. captcha (mews) is troubling me. Even user enters true captcha chars (no case-sensitive by config) I get the error message.
Here is my validator :
FYI: i have a table "user" instead of users, and i can use it nicely in other controllers.
protected function loginValidator()
{
$message = array(
'exists:user,username' => 'Wrong username/pass combination',
'exists' => 'Wrong :attribute.',
'required' => ':attribute cannot be empty',
'captcha' => 'Wrong captcha'
);
return Validator::make(Input::all(),[
'usernameInput' => 'required|exists:user,username',
'passwordInput' => 'required',
'captchaInput' => 'captcha|required'
], $message);
}
Even if username/pass combination is true, i get wrong captcha message.
Thanks in advance.
protected function loginValidator()
{
$validator = Validator::make(
array(
'name' => 'Dayle',
'password' => 'lamepassword',
'email' => 'email#example.com'
),
array(
'name' => 'required',
'password' => 'required|min:8',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
$data['messages'] = $validator->messages()->all();
}
else
{
//complete validation
}
return View::make('home.login', $data);
}
I have a registration form that I'm creating using the blade templating like so:
{{ Form::open(array('url'=>'registerUser', 'method'=>'POST', 'class'=>'loginForm SignUp')) }}
In routes.php, I have the following route:
Route::post('registerUser', 'UsersController#doRegister');
But when I submit the form, I get a MethodNotAllowedHttpException. Pretty much every other question I've found online about this was a case of the form having the GET method while the route had POST, but mine match, so I'm pretty confused.
Edit: Here's my full routes file:
Route::get('', 'UsersController#showLogin');
Route::get('login', 'UsersController#showLogin');
Route::post('doLogin', 'UsersController#doLogin');
Route::get('signUp', 'UsersController#showSignUp');
Route::post('authenticateCode', 'UsersController#authenticateCode');
Route::post('requestCode', 'UsersController#requestCode');
Route::get('showRegister', 'UsersController#showRegister');
Route::post('registerUser', 'UsersController#doRegister');
Route::get('dashboard', 'DashboardController#showDashboard');
Here's the controller function:
public function doRegister() {
$rules = array(
'fname' => 'required|alpha|min:2',
'lname' => 'required|alpha|min:2',
'email' => 'required|email|unique:users',
'phone' => 'required|alpha_num|min:7',
'company' => 'required|alpha_spaces|min:2',
'password' => 'required|alpha_num|between:6,12|confirmed', // these password rules need to be improved
'password_confirmation' => 'required|alpha_num|between:6,12'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->passes()) {
$user = User::create(array(
'fname' => Input::get('fname'),
'lname' => Input::get('lname'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
'phone' => Input::get('phone'),
'company' => Input::get('company')
));
// Update the invite key that was passed to the register page
// with this new user's ID.
$key = InviteKey::find(Input::get('key'));
$key->user_id = $user->id;
$key->save();
return Redirect::to('login')->with('message', 'Thank you for registering!');
} else {
return Redirect::to('register')
->with('message', 'The following errors occurred')
->withErrors($validator)
->withInput(Input::except('password'));
}
}
i want to give the user a visual feedback if they entered wrong login information.
public function doLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required|min:3'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userdata)) {
return Redirect::route('dashhome')
->withJsd('true');
} else {
return Redirect::route('login')
->withErrors(['wrongpw','Wrong E-mail address or Password']);
}
}
}
and on my login view i have this code
#if ($errors->has('wrongpw'))
<script>
$.gritter.add({
title: 'Ups!',
text: "{{ $errors->first('wrongpw') }}",
class_name: 'warning',
time: ''
});
</script>
#endif
But that doesn't work. Any idea what i make wrong or any suggestions on how to do it better?
Thanks
i think you are not passing errors in a correct associative array,
try
->withErrors(array('wrongpw' => 'Wrong E-mail address or Password'));
or
->withErrors(['wrongpw' => 'Wrong E-mail address or Password']);