Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

maan56's avatar

Ajax request error 422 (Unprocessable Entity)

Hey guys! I'm having issue with ajax request. I'm using jquery tabledit plugin and when saving edited row, facing error 422 (Unprocessable Entity) and in response text I get this error "{"message":"The given data was invalid.","errors":{"password":["New Password is required."]}}".

Here is my blade file. (after initiating table) jquery function

$.ajaxSetup({
            headers: {
                'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $('#editable').Tabledit({
            url: '{{ route("row_edit") }}',
            dataType:"json",
            type:"post",
            editButton: true,
            deleteButton: true,
            columns: {
                identifier: [10, 'id'],
                editable: [[5, 'pcs'], [6, 'weight'], [7, 'rate']]
            },
            restoreButton:false,
            onAjax: function(action, serialize) {
                // Executed before the ajax request If returns false, does not send the ajax request. (v1.2.2)
                console.log(serialize);
            },
            onSuccess:function(data, textStatus, jqXHR)
            {
                // Executed when the ajax request is completed
                console.log(data);
                console.log(textStatus);
                console.log(jqXHR);
            },
            onFail: function(jqXHR, textStatus, errorThrown) {
                // Executed when occurred an error on ajax request
                console.log("error");
                console.log(jqXHR);
            },
        });

on the controller side, I'm just returning same $request just to check wether the data is coming or not.

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

Any help would be appreciated. Thanks in Advance

0 likes
28 replies
tykus's avatar

Where is the actual payload (the form data) in the AJAX request; is it linked to the columns key?

maan56's avatar

@tykus this is jquery inline table edit plugin.

onAjax() function is called before AJAX request sent. and form data is serialized as I show it in console.

onSuccess() function is called when ajax request is completed successfully.

maan56's avatar

I checked in network tab in chrome browser and payload was there. and csrf_token was also shown in header

tykus's avatar

And is password in the Request payload?

maan56's avatar

@tykus this is payload

 columns: {
                identifier: [10, 'id'],
                editable: [[5, 'pcs'], [6, 'weight'], [7, 'rate']]
            },

where 5, 6, and 7 are table column index

tykus's avatar

Does your Request validation include a rule for password? Are you hitting the correct route?

maan56's avatar

@tykus @laracoft Here is my entire controller method. I didn't apply validation yet.

class ClientController extends Controller
{
	public function bookings($id){
		$date = Carbon::now()->toDateString();
		$cData = CourierData::whereDate('created_at', $date)->where([
			['client_id', '=', $id]
		])->get();
		return view('client.bookings')->with([
			'cData' => $cData,
			'date' => $date,
			'client_id' => $id,
		]);
	}
	
	public function bookingSearch(Request $request){
		$start = Str::before($request->selectedDate, ' -');
		$end = Str::after($request->selectedDate, '- ');
		$date = $request->selectedDate;
		if ($start === $end) {
$data = CourierData::whereDate('created_at', $start)->where([
                    ['client_id', '=', $request->client]
                ])->get();
                    if ($data->isEmpty()) return redirect()->back()->with('warning', 'There is no record in this date!');
                    else {
                        return view('client.bookings')->with([
                            'cData' => $data,
                            'date' => $date,
                            'client_id' => $request->client,
                        ]);
                    }
		} else {
			$data = CourierData::whereBetween('created_at', [$start, $end])->where([
				['client_id', '=', $request->client]
			])->get();
			if ($data->isEmpty()) return redirect()->back()->with('warning', 'There is no record in this date!');
			else {
				return view('client.bookings')->with([
					'cData' => $data,
					'date' => $date,
					'client_id' => $request->client,
				]);
			}
		}
	}

	public function bookingUpdate(Request $request){
        	if($request->ajax()){
            	return response()->json($request);
        	}
    	}
}

Route File:

Route::prefix('client')->group(function(){
	Route::get('/{client}/bookings', 'ClientController@bookings')->name('client.bookings');
	Route::post('/{client}/bookings', 'ClientController@bookingSearch')->name('client.bookings_date');
	Route::post('/bookingEdit', 'ClientController@bookingUpdate')->name('row_edit');
});
laracoft's avatar

Do you have another route by the name of row_edit somewhere? Try changing the route name client_booking_row_edit in your Route file and JS route("client_booking_row_edit")

maan56's avatar

@laracoft I tried changing route name and by passing direct URL too. same error

laracoft's avatar

@maan56 if you use this, do you still get the error?

public function bookingUpdate(Request $request){
	return "{}";
}
maan56's avatar

yes, same error. tried it already

laracoft's avatar

@maan56 how about this? still 422?

public function bookingUpdate(Request $request){
	throw new \Exception("this exception is thrown by code from Laracast");
}
laracoft's avatar

@maan56

Put in more effort to find the other row_edit. Do a global search if you have to.

Why is the exception this exception is thrown by code from Laracast not thrown? Because the code did not run, something else did.

maan56's avatar

Even I tried making new controller and use different method name and route name. but getting same 422 unprocessable entity error. Having responseText {"message":"The given data was invalid.","errors":{"password":["New Password is required."]}}

laracoft's avatar

Look in your browser developer console, what is the URL that the AJAX is loading?

maan56's avatar

This is console error:

POST http://127.0.0.1:8000/client/bookingEdit 422 (Unprocessable Entity)

also check network tab, and request headers and form-data. everything is fine. but I don't know why this happening.

laracoft's avatar
  1. Do this:
Route::prefix('client')->group(function(){
	Route::get('/{client}/bookings', 'ClientController@bookings')->name('client.bookings');
	Route::post('/{client}/bookings', 'ClientController@bookingSearch')->name('client.bookings_date');
	Route::post('/bookingEdit', function(){
		throw new \Exception("this exception is thrown by code from Laracast");
	})->name('row_edit');
});
  1. If it doesn't not help, show your entire web.php route file
maan56's avatar

Here is ajax funtion in jquery.tabledit.js file I'm using:

/**
         * Send AJAX request to server.
         *
         * @param {string} action
	* action can be 'edit' or 'delete'
         */
        function ajax(action)
        {
            var serialize = $table.find('.tabledit-input').serialize() + '&action=' + action;

            var result = settings.onAjax(action, serialize);

            if (result === false) {
                return false;
            }

            var jqXHR = $.post(settings.url, serialize, function(data, textStatus, jqXHR) {
                if (action === settings.buttons.edit.action) {
                    $lastEditedRow.removeClass(settings.dangerClass).addClass(settings.warningClass);
                    setTimeout(function() {
                        //$lastEditedRow.removeClass(settings.warningClass);
                        $table.find('tr.' + settings.warningClass).removeClass(settings.warningClass);
                    }, 1400);
                }

                settings.onSuccess(data, textStatus, jqXHR);
            }, 'json');

            jqXHR.fail(function(jqXHR, textStatus, errorThrown) {
                if (action === settings.buttons.delete.action) {
                    $lastDeletedRow.removeClass(settings.mutedClass).addClass(settings.dangerClass);
                    $lastDeletedRow.find('.tabledit-toolbar button').attr('disabled', false);
                    $lastDeletedRow.find('.tabledit-toolbar .tabledit-restore-button').hide();
                } else if (action === settings.buttons.edit.action) {
                    $lastEditedRow.addClass(settings.dangerClass);
                }

                settings.onFail(jqXHR, textStatus, errorThrown);
            });

            jqXHR.always(function() {
                settings.onAlways();
            });

            return jqXHR;
        }

See if this file can help

tykus's avatar

Can you check the Network tab in your Browser's devtools whenever you submit the form, check that the URL is /client/bookingEdit - as mentioned above, it would appear that you are not posting to the expected?endpoint

laracoft's avatar

@tykus his console error shows 🤷‍♂️🤷‍♂️🤷‍♂️

POST http://127.0.0.1:8000/client/bookingEdit 422 (Unprocessable Entity)
maan56's avatar

I used another working ajax request with this and that was working. I don't know why this request was broken. and throwing error.

That ajax request was on another controller and I use the same route for both requests with an additional parameter named route_method to separate both requests. And that is working perfectly. Thanks to all of you!

tykus's avatar

That ajax request was on another controller and I use the same route for both requests with an additional parameter named route_method to separate both requests.

Wait, what?

2 likes
laracoft's avatar

@tykus I would actually let it rest, it's an /incomprehensible situation 🤦‍♂️

1 like

Please or to participate in this conversation.