Trying to make a simple post on laravel using AJAX. Here is my form :
<form id = "formNewsletter" name="formNewsletter" class="newsForm">
<div class="wrapperNewsletter">
<input type="text" name="email" id="email" placeholder="Your email address" />
<button name="submit" type="submit" class="btn">> Submit Newsletter</button>
</div>
</form>
Here is my javascript code:
$('#formNewsletter').on('submit',function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault(e);
$.ajax({
type:"POST",
url:"NewslettersController/create",
dataType: "json",
data: $(this).serialize(),
success: function(response){
console.log(response);
},
error: function(response){
console.log(response);
}
})
});
Note that x-csrf-token is declared inside meta tag on head file. Here is the code for controller:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CreateNewsletterRequest;
use App\Newsletter;
class NewslettersController extends Controller
{
/**
* @param CreateNewsletterRequest $request
* @throws \Exception
*/
public function create(CreateNewsletterRequest $request) {
$newsletter = new Newsletter;
$newsletter->email = $request->input('email');
$newsletter->remember_token = $request->input('_token');
if (Newsletter::where('email', '=',$request->input('email'))->count() == 0) {
$newsletter->save();
}
else {
throw new \Exception('Error! '.$request->input('email') .'already exists on database', Response::HTTP_CONFLICT);
exit();
}
}
}
The problem is that when I submit the form, no matter if I insert any email on form or not, I get on console the following : Object { code: 0, text: "" }
EDIT: I've forgot to mention the handler code, on Exceptions\Handler.php that looks as following:
public function render($request, Exception $e)
{
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse(array('code' => $e->getCode(), 'text' => $e->getMessage()));
}
return parent::render($request, $e);
}
This code works great for exceptions from controller but not for validation errors. How can I handle the validation errors on Handler.php? It seems like getMessage is not working, it doesn't return the validation error message. From the handler I get the right response for this exception: throw new \Exception('Error! '.$request->input('email') .'already exists on database', Response::HTTP_CONFLICT);
via Miril Terolli