Data-request-redirect using value from the ajax Handler response

Hello everyone,

How can I use data-request-redirect to redirect to a page that expects a URL parameter, where that parameter is generated by the component’s AJAX handler?

For example, I have a handler called onCreateItem that creates an element from the Item model.

The component’s response is:

return [
    'success' => true,
    'message' => 'Item created successfully',
    'item_id' => $item->id,
    'item_uniq_name' => $item->item_uniq_name
];

I’d like to use data-request-redirect so that after the Ajax operation completes, the user is redirected to /site/item-details/item_id.

I’d prefer not to do the redirect from the component itself, since the handler may be used in different parts of the site, and redirection isn’t always required. So this responsibility should fall on the front end.

To start with, I already have the item-details page configured with the URL /site/item-details/:item_id, so the page is ready to receive that parameter.

Best regards, and thanks!

Hi @sanPuerquitoPrograma

I would not use the data-request-redirect nor the data-attributres in this case and replace it all with Javascript handling, and then implement the redirect inside the success method in js with a simple window.location.url=.

I found a solution roadmap. In the button, using Data API

<button 
    data-request="onCreateItem"
    data-request-success="handleRedirect(data)">
    Crear item
</button>

and, a minimal script to handle the redirect

<script>
    function handleRedirect(data) {
        if (data.success && data.item_id) {
            window.location.href = 'site/item-details/' + data.item_id;
        } else {
            alert('ups!');
        }
    }
</script>

Greetings from Mexico