Reputation: 749
I'm trying to have a form send emails in a Laravel project. However, I keep receiving 500 error. I'm following this tutorial.
This is the route:
Route::post('contact', 'PagesController@contact');
This is the controller:
public function contact(Request $request) {
$this->validate($request, [
'email'=>'required|email',
'fullname'=>'max:50'
]);
$data = array(
'email' => $request->email,
'fullname' => $request->fullname,
);
Mail::send('emails.contact', $data, function($message) use ($data){
$message->from($data['email']);
$message->to('[email protected]');
});
}
This is the view that contains the HTML form with the CSRF as noted by previous questions.
<form onsubmit="return false" method="post" id="contact_form" name="contact-form">
<input type="hidden" name="_token" value="{{ csrf_field() }}">
<input type="text" class="form-control" name="fullname" id="fullname" required>
<input class="form-control" aria-describedby='sizing-addon1' placeholder="Email Address" required name="email" id="email">
<button id="contact_btn" data-loading-text="Sending" >Send Your Message</button>
</form>
This is the AJAX code:
$('#contact_form').submit(function(e) {
e.preventDefault();
}).validate({
rules: {
fullname: {
required: true,
},
email: {
required: true,
email: true
},
},
submitHandler: function (form) {
var btn = $('#contact_btn');
btn.button('loading');
setTimeout(function() {
btn.button('reset');
}, 8000);
$.ajax({
type: 'POST',
url: "{{url('contact')}}",
dataType: 'json',
async: true,
data: {
fullname: $('#fullname').val(),
email: $('#email').val(),
},
success: function (json) {
$('#contact').hide();
$('#output').html(
'<p>We have received your message!</p>'
).show();
}
});
return false;
}
});
in Chrome dev tools:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Upvotes: 0
Views: 650
Reputation: 2604
I think the problem is in this line:
<input type="hidden" name="_token" value="{{ csrf_field() }}">
You should use csrf_token()
not csrf_field()
because the last one generate the csrf input field and the first one only token.
Also add token to ajax request in your data:
data: {
...
'_token':$('[name="_token"]').val(),
...
}
or in ajax header before calling ajax function:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
Upvotes: 1