Laravel 5.3 - My goal is to send login form via ajax to login controller (AuthenticatesUsers trait), and to get a response (json would be ok), so i could set timeout before redirect to "dashboard" section (authenticated). I need that timeout for some frontend stuff.
So could it be done? If it could, hint would suffice.
Thanks in advance.
Javascript example:
$("#login-form").submit(function (e) {
var url = "/login"; // the script where you handle the form input.
$.ajax({
type: "POST",
cache : false,
url: url,
data: $("#login-form").serialize(), // serializes the form's elements.
success: function ()
{ //Do the timeout part, then redirect
topbar.addClass('success');
form.addClass('goAway');
article.addClass('active');
tries = 0;
},
error: function () {
location.reload();
input.addClass('disabled');
topbar.addClass('error');
}
});});
Login form is sent via post, and i would like to do a redirect by myself, not via controller, and my main concern is the csrf token on javascript redirect would change.
edit:
Another thing that I discovered is including token inside ajax setup:
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': _token}
});
and prevent form default action:
$("#login-form").submit(function (e) {
e.preventDefault();
Here's my login form (all js and css is included in parent view):
#extends('layouts.app')
#section('content')
<form class="form form-horizontal" id="login-form" role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="forceColor"></div>
<div id="logosm_wrapper">
<img id="logosm_login" src="img/ipism_100x50.png" alt="logo" >
</div>
<div class="forceColor"></div>
#if (count($errors))
<div class="topbar error">
#else
<div class="topbar">
#endif
<div class="spanColor"></div>
<input id="email" type="email" class="input form-control" name="email" placeholder="E-mail" value="{{ old('email') }}">
</div>
#if (count($errors))
<div class="topbar error">
#else
<div class="topbar">
#endif
<div class="spanColor"></div>
<input id="password" type="password" class="input form-control" name="password" placeholder="Password"/>
</div>
<button class="submit" id="submit">Login</button>
<!--input class="submit" id="submit" type="submit" value="Login"-->
</form>
#endsection
This is working as intended by Laravel Auth, my intention was to green out input fields on authorisation via JS, and then redirect user to dashboard...
I suggest u add this in your ajax:
$.ajax({
....
async : false,
....
Related
I want to send the password encrypted to the server side script, and after match the pasword encrypted with the password on the database, if the passords match, redirect the user to the home page.
My Jquery function:
jQuery('#login_form').submit(function(){
var form_data = new FormData();
form_data.append('login', $('#lg-user').val());
form_data.append('password', CryptoJS.MD5($('#lg-password').val()));
jQuery.ajax({
type: "POST",
url: "processa.php",
data: dados,
success: function( data )
{
alert( data );
}
});
return false;
});
The form:
<form action="" id="login_form" method="post">
<?php
session_start();
if (isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" name="username" class="form-control"
placeholder="usuario">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="password" name="password" class="form-control"
placeholder="senha">
</div>
<div class="col-md-12">
<div class="text-center">
<input type="submit" value="Entrar" class="btn login_btn">
</div>
</div>
</form>
The problem is that everytime i send the form, the page reload.
Your approach is highly insecure.
By encrypting it client-side and matching what it sent with the DB, you are sending the data that "proves" the user is who they say they are to the server, so if someone were to get hold the database they would know what to send.
Also, MD5 is far too weak to secure a password today.
To keep the password safe in transmission to the server: Use HTTPS.
To keep the passwords in your database safe: hash them server-side as described in the Safe Password Hashing FAQ in the PHP manual.
To stop the regular form submission when you use the submit event to intercept it and use Ajax:
Capture the event object
Call preventDefault on it
Such:
jQuery('#login_form').submit(function(e){
e.preventDefault()
Hello I want to get the value of this input and fetch it using ajax no database at all. thank you. how can i do it with ajax?
<form method="POST">
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</form>
there is my inputs and here is the button.
<form action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt" onchange = "change()"></textarea><br><br><br>
<input class="btn btn-primary btn-lg" type="submit" name="btnSubcode" value="PROCESS"></input>
</div>
</div>
</div>
</div>
</form>
so the final output sould not refresh the page and the textarea value will be send to the textbox
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process.
http://malsup.com/jquery/form/#getting-started
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
// prepare Options Object
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
};
// pass options to ajaxForm
$('#myForm').ajaxForm(options);
Firstly, rewrite your html code as below:
<form id="form" action="top-up.php" method="POST">
</div>
</div>
<div class="col-md-6" style="margin-top: -160px">
<div class="caption">
<div class="jumbotron">
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
<input class="btn btn-primary btn-lg js-form-submit" type="submit"></input>
</div>
</div>
</div>
</div>
</form>
Then, you can write JS something like this:
$(document).on('click','.js-form-submit', function (e) {
e.preventDefault();
var formData = $('#form').serialize();
var url = $('#form').attr('action');
$.ajax({
type: "POST",
cache: false,
url: url // Your php url here
data : formData,
dataType: "json",
success: function(response) {
//var obj = jQuery.parseJSON(response); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
});
I am using http://www.formvalidator.net/index.html to validate my form but the form gets submitted even when the validation get failed.
Form code:
<form name="add-todo" class="form-horizontal" action="" method="post">
<h5>Add New Item</h5>
<div class="form-group">
<div class="col-md-12">
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-add">Add</button>
</div>
</div>
</form>
jQuery code:
$(document).ready(function() {
$.validate({
modules: 'security'
});
$('form[name=add-todo]').submit(function(e) {
e.preventDefault();
var text = $("#todo-text-input").val();
$('.btn-add').text('Saving ....');
$.ajax({
url: this.action,
type: this.method,
data: {
text: text
},
success: function(response) {
$("#todo-text-input").empty();
$('.messages').removeClass('hide-element');
$('.alert').addClass('alert-success');
$('.alert').text('To do item added successfully.');
$('.alert').fadeTo(2000, 500).slideUp(500, function() {
$('.alert').slideUp(500);
});
}
});
});
});
dont use submit button. You can use
<button type="button" class="btn btn-primary btn-add">Add</button>
after that check your validation status. if its valid then submit the form.
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
In your input field you don't need to use data-validation="required" just use required like
<input type="text" required class="form-control" id="todo-text-input" name="todo-text">
Please change you form validation code configuration like this:
$.validate({
form : '#registration-form',
modules : 'security',
onSuccess : function($form) {
alert('The form '+$form.attr('id')+' is valid!');
// write your ajax code to submit form data on server
return false; // Will stop the submission of the form
}
});
For more info follow:
http://www.formvalidator.net/index.html#configuration
I am developing an application in ExpressJS, and plan to have the following HTML code in a jade file.
I have the following page with 4 form buttons:
<div class="dog">
<div class="dog_wrapper clearfix">
<div class="col-lg-6 col-md-6 col-sm-6 left_sec">
<div class="panel-heading">LIVE</div>
<div class="col-md-6 col-sm-6">
<div class="livefeed-left">
<form class="button" method="post">
<input type="hidden" value="DEPLOY" id="fieldID" name="fieldName"/>
<input type="submit" value="Raise"/>
</form>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="livefeed-right">
<form class ="button" method="post">
<input type="hidden" value="RECOVER" id="fieldID" name="fieldName"/>
<input type="submit" value="Lower"/>
</form>
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 right_sec">
<div class="panel-heading" id="sample" style="width: 100%; height:500px">MAP</div>
<div class="col-md-6 col-sm-6">
<div class="livefeed-left">
<form class= "button" action="" method="post">
<input type="hidden" value="UPLOAD" id="fieldID" name="fieldName"/>
<input type="hidden" value="" id="lngHolderID" name="lngHolderName"/>
<input type="hidden" value="" id="latHolderID" name="latHolderName"/>
<input type="hidden" value="" id="altHolderID" name="altHolderName"/>
<input type="hidden" value="" id="actHolderID" name="actHolderName"/>
<input type="hidden" value="" id="actParamHolderID" name="actParamHolderName"/>
<input type="submit" value="Upload" onclick="compileHolder()"/>
</form>
</div>
Each button will POST an action,however, it refreshes the page every time the user clicks on the button. I read on a separate post that this can be controlled through jQUERY or AJAX.
I added the following script at the end before the tag:
<script type="text/javascript">
$('.button').on('submit', function (event) {
event.preventDefault(); // Stop the form from causing a page refresh.
var data = {
username: $('#username').val(),
password: $('#password').val()
};
$.ajax({
url: 'http://localhost/my/url',
data: data,
method: 'POST'
}).then(function (response) {
// Do stuff with the response, like add it to the page dynamically.
$('body').append(response);
}).catch(function (err) {
console.error(err);
});
});
</script>
</body>
</html>
My question is for the following section:
$('upload').on('submit', function (event) {
event.preventDefault(); // Stop the form from causing a page refresh.
var data = {
username: $('#username').val(),
password: $('#password').val()
};
$.ajax({
url: 'http://localhost/my/url',
data: data,
method: 'POST'
}).then(function (response)
Would the above code work? Also, does url: 'http://localhost/my/url' take in the actual jade file. For example, dogshow.jade?
Sorry for the questions, I am pretty new at this and still feeling my way around.
No this will not work. If u want to send all form data as u name assigned in form just use single line.
var data = $('#upload').serialize();
Shouldn't $('upload') be $('#upload')? In jQuery id's are preceded by # sign.
I'm using Ajax to submit the login form without refreshing the page. I've added a function to see whether the data returns 'error' (which comes up when the user enters an incorrect email/password). If it does not return 'error', the user has been logged in and will be transferred to the page within 2 seconds.
The problem is that my button acts like a double-click button and I cannot see why. This is my JS file:
$(function() {
$("#goLogin").click(function() {
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
});
function finishLogin( data , textStatus ,jqXHR ) {
if ( data == "error" ) {
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
} else {
$('.succesMsg').fadeIn(500).show();
$('.errorMsg').fadeOut(300).hide();
setTimeout("location.href = 'protected.php';",2000);
}
}
I've tried placing it between the document_ready tags, but that isn't working either.
Part of the HTML code:
<div class="login form">
<div class="login-header">Please Login</div>
<form method="post" id="loginForm" name="form">
<label for="email" class="short">Email*</label>
<input type="text" name="email" id="email" class="required" placeholder="" />
<label for="password" class="short">Password *</label>
<input type="password" name="password" id="password" class="required" placeholder="" maxlength="15" />
</form>
<div id="login-functions">
<div class="loginbtn-container">
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Login" />
</div>
<div class="login form actions">
<p class="register account">Register an account</p>
<p class="request password">Lost your password?</p>
</div>
</div>
</div>
<div class="errorMsg">Incorrect. Please recheck your details</div>
<div class="succesMsg"><b>You've been logged in!</b> Please wait while we transfer you</div>
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
did you mean tto hide both? I see the click is working fine, though you should ideally do submit
Take your submit inside the form, and prevent normal form submit using preventDefault()
$("#goLogin").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
Please move your submit button inside the form closing tag first
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Inloggen" />
The above button is placed after the </form> tag.
Because you click on input type submit and progress Ajax on it; it cause submit 2 times.
To avoid it, you can use as Zach Leighton said above ; or use as below
$("#goLogin").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});