validation - Errors are not displaying in Ajax with laravel5 -
when i'm trying return error or make form returns error inputs. doesn't return (i've tried use console.log
, it's working fine), when success part, message returns success. errors not appending <ul>
tag. why that? please see 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="{{ csrf_token() }}" /> <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="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></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' ]);
Comments
Post a Comment