I am trying to send an ajax post request in my page, but I'm getting an error in console.
POST http://local.bazaar.com/testimonials/submit 500 (Internal Server Error)
Routes.php
Route::post('/testimonials/submit','TestimonialsController@savetesti');
Ajax.js
$("#submitTestimonial").click(function() {
$.ajax({
url: '/testimonials/submit',
method: 'POST',
success: function(data) {
alert(data);
die;
}
})
return false;
});
TestimonialsController.php
<?php
namespace App\Http\Controllers;
use Input;
use Request;
class TestimonialsController extends Controller
{
/**
* Perform validations on user data
* Hash Password
* Create
* @return Response
*/
public function savetesti()
{
// Getting all post data
print_r("success");
}
}
?>
viewPage->
<div class="testimonialForm">
<form action="#" method="POST">
<div class="testimonialFormTitle">Write A Testimonials</div>
<a class="closeTestimonialBtn"></a>
<p><input type="text" placeholder="Your Name" id="tname" name="name" class="inputTxt placeholder"></p>
<p><input type="text" placeholder="Your Email" id="temail" name="email" class="inputTxt placeholder"></p>
<p><textarea placeholder="Testimonial" cols="50" rows="6" id="tmessage" name="message" class="inputTxtArea placeholder"></textarea></p>
<a class="greyBtn" id="submitTestimonial" href="#">Submit</a>
</form>
</div>
I think the problem is the csrf token.
When you do a post request there should always be a csrf token.
If you have created a form with illuminate/html facade then its quite simple
{!! Form::open() !!}
{!! Form::close() !!}
If you do not have illuminate/html go to your composer.json file and add
"illuminate/html": "~5.0",
In the require block after laravel. After that run composer update and go to /config/app.php here you should add a new provider and alias
'providers' => [
'Illuminate\Html\HtmlServiceProvider',
],
'aliases' => [
'Form' => 'Illuminate\Html\FormFacade',
],
Now inside this form there is a hidden input field with the crsf token.
In you javascript file you can get this code with something like.
var data = {};
data._token = $('[name="_token"]').val();
Then send the data object with the ajax post call
$.ajax({
url: '/testimonials/submit',
method: 'POST',
data: data,
success: function(data){
alert(data);
}
});
And for test purpose you could change your function
public function savetesti()
{
return 'success';
}