Я пытаюсь отправить данные на мой контроллер Laravel с помощью Ajax, но я получаю сообщение об ошибке «422 (Unprocessable Entity)».
Я немного погуглил, и я думаю, что это связано с передачей JSON, но я не уверен, как ее решить.
Ниже приведено то, что я считаюсоответствующая информация:
Сценарий
$("#addStepNew").click(function() {
var step_ingredients = JSON.stringify(stepIngredients)
var step_description = $('#stepDescription').val();
var prep_step = $('input[name=prepStep]:checked').val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: "ingredients="+step_ingredients+"&description="+step_description+"&is_prep="+prep_step+"step_no=1",
dataType:'json',
url: "{{ route('ingredients.store', ['id' => $recipe->id]) }}",
success:function(data){
console.log(data);
$("#output").html('<div class="alert alert-success my-0">'+data.name+' added</div>');
$("#output").toggleClass("invisible")
$("#output").fadeOut(2000);
}
});
});
console.log(stepIngredients)
дает [{"ingredient_id":"9","ingredient_quantity":"3","Ingredient_units":"kilograms"}]
Идея состоит в том, чтобы передать все это моемуконтроллер, и записать значения в БД, но в данный момент я даже не могу передать информацию.
Я сделал следующее с моим контроллером:
public function store(Request $request)
{
//$this->validate($request);
/*
$step = new Step;
$step->recipe_id = $request->recipe_id;
$step->step_no = $request->step_no;
$step->method = $request->description;
$step->save();
*/
$data = [
'success' => true,
'message'=> 'Your AJAX processed correctly',
] ;
return response()->json($data);
}
Итак, насколько я понимаю (я учу себя этому на ходу), если AJAX успешно пройден,тогда он должен вернуть сообщение об успехе и вывести его в моем #output div
?
+--------+-----------+--------------------------+--------------------+------------------------------------------------------------------------+--------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+-----------+--------------------------+--------------------+------------------------------------------------------------------------+--------------+
| | GET|HEAD | / | | App\Http\Controllers\PagesController@index | web |
| | GET|HEAD | api/user | | Closure | api,auth:api |
| | GET|HEAD | home | home | App\Http\Controllers\HomeController@index | web,auth |
| | GET|HEAD | login | login | App\Http\Controllers\Auth\LoginController@showLoginForm | web,guest |
| | POST | login | | App\Http\Controllers\Auth\LoginController@login | web,guest |
| | POST | logout | logout | App\Http\Controllers\Auth\LoginController@logout | web |
| | POST | password/email | password.email | App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail | web,guest |
| | GET|HEAD | password/reset | password.request | App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm | web,guest |
| | POST | password/reset | | App\Http\Controllers\Auth\ResetPasswordController@reset | web,guest |
| | GET|HEAD | password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController@showResetForm | web,guest |
| | GET|HEAD | recipes | recipes.index | App\Http\Controllers\RecipesController@index | web,auth |
| | POST | recipes | recipes.store | App\Http\Controllers\RecipesController@store | web,auth |
| | GET|HEAD | recipes/create | recipes.create | App\Http\Controllers\RecipesController@create | web,auth |
| | GET|HEAD | recipes/{id}/ingredients | ingredients.create | App\Http\Controllers\IngredientsController@create | web,auth |
| | POST | recipes/{id}/ingredients | ingredients.store | App\Http\Controllers\IngredientsController@store | web,auth |
| | GET|HEAD | recipes/{id}/steps | steps.create | App\Http\Controllers\StepsController@create | web,auth |
| | POST | recipes/{id}/steps | steps.store | App\Http\Controllers\StepsController@store | web,auth |
| | PUT|PATCH | recipes/{recipe} | recipes.update | App\Http\Controllers\RecipesController@update | web,auth |
| | DELETE | recipes/{recipe} | recipes.destroy | App\Http\Controllers\RecipesController@destroy | web,auth |
| | GET|HEAD | recipes/{recipe} | recipes.show | App\Http\Controllers\RecipesController@show | web,auth |
| | GET|HEAD | recipes/{recipe}/edit | recipes.edit | App\Http\Controllers\RecipesController@edit | web,auth |
| | POST | register | | App\Http\Controllers\Auth\RegisterController@register | web,guest |
| | GET|HEAD | register | register | App\Http\Controllers\Auth\RegisterController@showRegistrationForm | web,guest |
| | GET|HEAD | tags | tags.index | App\Http\Controllers\TagsController@index | web,auth |
| | POST | tags | tags.store | App\Http\Controllers\TagsController@store | web,auth |
| | GET|HEAD | tags/create | tags.create | App\Http\Controllers\TagsController@create | web,auth |
| | GET|HEAD | tags/{tag} | tags.show | App\Http\Controllers\TagsController@show | web,auth |
| | PUT|PATCH | tags/{tag} | tags.update | App\Http\Controllers\TagsController@update | web,auth |
| | DELETE | tags/{tag} | tags.destroy | App\Http\Controllers\TagsController@destroy | web,auth |
| | GET|HEAD | tags/{tag}/edit | tags.edit | App\Http\Controllers\TagsController@edit | web,auth |
+--------+-----------+--------------------------+--------------------+------------------------------------------------------------------------+--------------+