AJAX Forms

A majority of the default forms that come in the package use AJAX for validation. The concept is simple, if there is a 422 response, it will show a red error alert along with the message, and highlight the form fields accordingly. If the submission was successful, it will show a success message, redirect, reload the page, or some other specified function.

In order to utilize the AJAX forms, just specify that the form should use AJAX by adding data-ajax-form to it:

<form method="POST" action="{{ route('admin.roles.create') }}" novalidate data-ajax-form>
    @csrf
    ...

Also note the use of novalidate, which is used to disable default browser validation.

Responses

Once an AJAX form submission is successful, you will want to provide an appropriate response in the form of json():

return response()->json(['reload_page' => true]);

There are several acceptable JSON responses that are supported out of the box with LAP.

redirect

This will redirect the user to the provided URL.

return response()->json(['redirect' => route('admin.roles')]);

It is also recommended that you use the flash() helper method beforehand if the user will be leaving/reloading the current page they are on after the form is submitted:

flash(['success', 'Role created!']);

return response()->json(['redirect' => route('admin.roles')]);

The first array element contains the Bootstrap 4 alert- class e.g. success, andd the second contains the message that will be displayed.

reload_page

This will reload the current page the user is on. Useful for clearing form contents and resetting the request.

return response()->json(['reload_page' => true]);

reload_datatables

This will reload datatables on the page so that their contents are refreshed. Useful when doing things like deleting rows so that the current position of the page is maintained and not reloaded.

return response()->json(['reload_datatables' => true]);

flash

If your response will be keeping the user on the same page, you may still want to flash them a message. This can be done by calling flash within the json response itself.

return response()->json(['flash' => ['success', 'Role deleted!']]);

Notice how the format is exacly the same as using the flash() helper function. The first array element is the BS4 alert- class, and the second is the message to display.

Custom Responses

If you want to support more json responses via javascript/jquery, you can do so by utilizing the ajaxComplete() method:

$(document).ajaxComplete(function (event, xhr, settings) {
    if (xhr.hasOwnProperty('responseJSON') && xhr.responseJSON.hasOwnProperty('do_my_function')) {
        console.log(xhr.responseJSON.do_my_function);
    }
});