When I'm trying to return an error or to make the form returns error for inputs. It doesn't return something (I've also tried to use console.log
and it's working fine), but when the success part, the message returns success. The errors are not appending into the <ul>
tag. Why is that? Please see my code below.
register.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="" />
<title>Document</title>
<style>
*{
font-family: arial, sans-serif;
}
body{
background: lightslategray;
}
.container-fluid{
width: 1100px;
margin: 0 auto;
border-radius: 3px;
background: #fff;
padding: 15px 20px;
min-height: 700px;
}
form ul, .alert ul{
padding-left: 0;
}
form ul li{
list-style: none;
margin-bottom: 10px;
}
.alert{
display: none;
color: #c11111;
background: #ffe4e8;
padding: 10px 20px;
}
.alert ul li{
list-style: none;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="alert">
<ul></ul>
</div>
<form action="" method="post">
<ul>
<li>
Username<br>
<input type="text" name="username" id="username">
</li>
<li>
Password<br>
<input type="password" name="password" id="password">
</li>
<li>
Password Again<br>
<input type="password" name="password_again" id="password_again">
</li>
<li>
Email<br>
<input type="email" name="email" id="email">
</li>
<li>
<button type="submit">Submit</button>
</li>
</ul>
</form>
</div>
<script src="http://ift.tt/2n9t8Vj"></script>
<script>
$(document).ready(function(){
var alerts = $('.alert');
$('form').submit(function(e){
e.preventDefault();
// formData
var formData = new FormData();
formData.append('username', $('#username').val());
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: 'registers',
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: formData,
success: function(data){
alerts.hide().find('ul').empty();
if(!data.success){
$.each(data.errors, function(index, error){
alerts.find('ul').append('error');
});
alerts.slideDown();
} else{
alerts.find('ul').append('Success');
alerts.slideDown();
}
},
error: function(){}
});
});
});
</script>
</body>
</html>
AuthController.php
public function postRegister(){
$validator = Validator::make(
[
'username' => Input::get('username')
],
[
'username' => 'required|max:6|min:3'
]
);
if($validator->fails()){
return Response::json([
'success' => false,
'error' => $validator->errors()->toArray()
]);
}
// if validated
return Response::json(['success' => true]);
}
routes.php
// Using jQuery
Route::get('/register', [
'as' => 'auth.register',
'uses' => 'AuthController@getRegister'
]);
Route::post('/registers', [
'as' => 'auth.registers',
'uses' => 'AuthController@postRegister'
]);
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire