Responses
The response object defines how the server responds to AJAX requests. The response methods are listed below.
Method - update()
Patch the DOM with some updates.
return ajax()->update(['#someElement' => 'HTML contents']);Method - data()
Provide data with the response.
return ajax()->data(['isSuccess' => true]);Method - redirect()
Redirect to another URL.
return ajax()->redirect('https://octobercms.com');Method - reload()
Reload the page.
return ajax()->reload();Method - flash()
Display a flash message.
return ajax()->flash("Great success!");Method - error()
Trigger an error with update lifecycle.
return ajax()->error("Well that didn't work!");Method - fatal()
Trigger an error that aborts the request.
return ajax()->fatal("Something broke!");Method - js()
Load JavaScript with the response.
return ajax()->js('/assets/js/widget.js');You can pass attributes as a second parameter, which is useful for loading ES modules or setting other script attributes.
// Load as an ES module
return ajax()->js('/assets/js/widget.js', ['type' => 'module']);
// With defer attribute
return ajax()->js('/assets/js/widget.js', ['defer' => true]);To load multiple scripts, pass an array of paths. The second parameter applies to all scripts.
return ajax()->js(['/assets/js/a.js', '/assets/js/b.js'], ['type' => 'module']);For different attributes per script, use an associative array where keys are paths and values are attribute arrays.
return ajax()->js([
'/assets/js/module.js' => ['type' => 'module'],
'/assets/js/legacy.js' => ['defer' => true],
]);Method - css()
Load a StyleSheet with the response.
return ajax()->css('/assets/css/widget.css');You can pass attributes as a second parameter.
// Media query
return ajax()->css('/assets/css/print.css', ['media' => 'print']);Multiple stylesheets with different attributes.
return ajax()->css([
'/assets/css/screen.css' => ['media' => 'screen'],
'/assets/css/print.css' => ['media' => 'print'],
]);Method - img()
Load an image with the response.
return ajax()->img('/assets/images/logo.png');Multiple images can be preloaded by passing an array.
return ajax()->img(['/assets/images/a.png', '/assets/images/b.png']);Method - browserEvent()
Triggers a browser event with the response.
return ajax()->browserEvent('app:stale-document');You can listen to this event in the browser using a generic listener. This example prompts the user before resubmitting the request with a force flag set in the data.
addEventListener('app:stale-document', function (event) {
if (confirm('Another user has updated this document, proceed?')) {
jax.request(event.target, 'onUpdate', { data: {
force: true
}});
}
});To prevent the partials from updating as part of the response, call preventDefault() on the event object.
addEventListener('app:stale-document', function (event) {
event.preventDefault();
});Method - browserEventAsync()
Triggers an asynchronous event to the browser where a promise is passed through with the event details.
This is useful when you want the JavaScript to wait before processing anything else. For example, showing an alert dialog before processing a redirect.
return ajax()
->browserEventAsync('sweet:alert', [
'message' => "You are about to be redirected to an external site"
])
->redirect('https://google.com');Then on the JS side. Wait for the alert to be dismissed and then resolve the provided promise.
addEventListener('app:sweet-alert', async function(event) {
const { promise } = event.detail;
await Swal.fire(...);
promise.resolve();
})Method - invalidFields()
Trigger invalid fields.
return ajax()->invalidFields(['name' => "The name field is required!"]);Method - partials()
Supply partials that were requested from the browser.
return ajax()->partials([
'site.header' => "New header contents",
'site.footer' => "New footer contents",
]);Method - exception()
Process an exception for common exception types.
try {
// ...
}
catch (Exception $ex) {
return ajax()->exception($ex);
}Override - registerCustomResponse
Let's define a custom class that introduces a sweetAlert method to the ajax() function.
return ajax()->sweetAlert("You did it!");First define your own custom AjaxResponse class inside your app.
namespace App\Classes;
class AjaxResponse extends \Larajax\Classes\AjaxResponse
{
public function sweetAlert($message)
{
return $this->browserEvent('app:sweet-alert', [
'type' => 'success',
'message' => $message
]);
}
}Then inside a service provider registration method, call the App::bind method to replace the AjaxResponse class by resolving to the custom one.
public function register()
{
ajax()->registerCustomResponse(\App\Classes\AjaxResponse::class);
}Now when ajax() is called it will return your custom class.
Override - registerGlobalComponent
Register a component as global using the static registerGlobalComponent method found on the ajax() helper.
ajax()::registerGlobalComponent(\App\Components\GlobalComponent::class);