Laravel Package With JS to handle Ajax From Request.
- Via Composer [ composer require sudeep/formparse ]
- add "require" : { "sudeep/formparse": "dev-master" } in your composer.json and run [ composer update ]
-
Add Sudeep\FormParser\FormServiceProvider::class, in 'providers' array of config/app.php file.
-
Run [ php artisan vendor:publish --provider=FormServiceProvider ] in CLI. this will save the JS file in your public/assets folder.
-
Next you Can make your own traits to use wherever you want. Or, you can directly use it in you main controller. just add [ use Sudeep\FormParser\FormParse;] in your app\http\controllers\Controller.php.
-
link form.js to your blade.file
-
After you call ajax function .
*for this you have to keep same value of id attr. as that of name attr. [ input type='text' name='address' id='address' ]
*to show error you have to keep class name with (error-) prepended in same value of name attr. [ span class='error-address']
$(document).on('submit','.form-class', function(e){
e.preventDefault();
var data = getData($(this))
$.ajax({
method: "POST",
url: '/your/url/to/post,
data: { data: data },
}).done(function( res ) {
if(res == "ok"){
var url = "/url/to/redirect";
setTimeout($(location).attr('href', url),3000);
}
}).fail( function(res){
//this will fill last values in filed
values(data)
//this will show errors
getErrors(res)
})
})
-
Now in your Controller.
public function toDoSomething(Request $request){
$result = $this->getArray($request);
$result = $this->getObj($request);
-------------------------------- FOR VALIDATION -----------------------------------------------
$this->withValidate($result, $rules);
$this->withValidate($result, new FormRequest());