I am trying to post a form using jQuery $.post method but I am getting MethodNotAllowedHttpException error in Laravel framework. I understand that there is some mismatch in the type of request going to route/controller but I am unable to figure out where.
jQuery Call
$.post("create", $("#myForm").serialize(), function(data) {
var json=JSON.parse(data);
console.log(json);
});
Controller
class create extends Controller
{
//
public function createRecord(){
$test="test";
return $test;
}
}
Routes (web.php)
Route::post('create',array('uses'=>'create@createRecord'));
Make your route like this, if all your doing is passing the controller.
Route::post('create', 'create@createRecord');
This is the only thing I can suggest. See if that fixes it or not.
Try this
Create cors.php in your middleware to allow all requests
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
In middle ware of verifyCsrfToken.php add this
protected $except = [
//
'api/*',
];
In routes.php create route of your app
Route::group(['middleware' => 'cors'], function()
{
Route::post('api/create', 'create@createRecord');
});
Try to add csrf token to your ajax function. The syntax may not be correct but this is the logic.
$.post("create", $("#myForm").serialize(),"_token" : "{{csrf_token()}}", function(data) {
var json=JSON.parse(data);
console.log(json);
});