Michael
Michael

Reputation: 576

Laravel 5.4 422 (Unprocessable Entity) Ajax call

I am trying to store comments and display the result on the same page with an Ajax call. But I keep getting this error in my console

422 (Unprocessable Entity)

Let's start with my Comment model:

class Comment extends Model
{
    // fields can be filled
    protected $fillable = ['body', 'user_id', 'image_request_id'];

    /**
     * Get the user that owns the Comment.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Let's continue with my form:

{{ Form::open(['id' => 'storeComment', 'route' => ['comments.store'], 'method' => 'POST']) }}
{!! Form::textarea('body', null, ['class'=>'form-control', 'rows' => 3]) !!}
{!! Form::hidden('image_request_id', $imageRequest->id) !!}
{{ Form::submit('Add comment', array('class' => 'btn btn-success btn-lg btn-block')) }}
{{ Form::close() }}

Let's see out controller method: (CommentController.php)

public function store(CommentRequest $request)
{
    $comment = Auth::user()->comments()->save(new Comment($request->all()));

    $response = array(
       'status' => 'success',
       'comment' => $comment
    );

    return response()->json($response);
}

My rules method in me CommentRequest.php

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
    return [
        'body' => 'required|max:1000',
    ];
}

Let's see our ajax.js

$( document ).ready(function() {

        $('#storeComment').on('submit', function(e) {
            e.preventDefault();

            // Retrieve form data
            var formData = [];
            var data = $(this).serializeArray();
            $.each(data, function(index, field) {
                formData[field.name] = field.value;
            });

            // Post request with formData as data
            axios.post('/comments', formData).then(function(data) {
                console.log(data);
            });
        });
});

When I don't use ajax everything workes and the data is being stored.

EDIT 1 console.log(data) before post request result

0: {name: "_token", value: "1DYMMAjNAv9TqOM4ZSu8JRlVpIeImmSDcmXP4Yu7"}
1: {name: "body", value: "blabla"}
2: {name: "image_request_id", value: "2"}

EDIT 2 console.log(formData) result

body: "blabla"
image_request_id: "2"
_token: "1DYMMAjNAv9TqOM4ZSu8JRlVpIeImmSDcmXP4Yu7"

EDIT 3 error picture

screenshot error log in console

Upvotes: 0

Views: 766

Answers (1)

Nikola Gavric
Nikola Gavric

Reputation: 3543

I think the issue is in the wrongly named variable, it is not temp but rather formData, check the code below:

    $( document ).ready(function() {
        $('#storeComment').on('submit', function(e) {
            e.preventDefault();

            // Retrieve form data
            var formData = {};
            var data = $(this).serializeArray();
            $.each(data, function(index, field) {
                formData[field.name] = field.value;
            });

            // Post request with temp as data
            axios.post('/comments', formData).then(function(data) {
                console.log(data);
            });
        });
   });

Upvotes: 1

Related Questions