Skip to content

[LiveComponent] Add LiveResponse::data() to send data to the JavaScript that called an action - #3931

Open
Pechynho wants to merge 1 commit into
symfony:3.xfrom
Pechynho:feat-live-response-data
Open

Pechynho wants to merge 1 commit into
symfony:3.xfrom
Pechynho:feat-live-response-data

Conversation

@Pechynho

Copy link
Copy Markdown
Contributor
Q A
Bug fix? no
New feature? yes
Deprecations? no
Documentation? yes
Issues
License MIT

Calling a LiveAction from your own JavaScript with component.action() is documented and useful. But the action has no clean way to send a result back to the code that called it. Some examples where this is needed:

  • a JavaScript widget (an autocomplete, a map, a chart) asks the component for data;
  • an action saves something and the JavaScript needs the new id or a message;
  • an action checks something (is this name free?) and the JavaScript shows the answer.

The component already has everything the action needs: its props, its entities, its form. Today the options are:

  • Return a JsonResponse: the client does not see a component response, so it shows the error modal. The component does not re-render, so every LiveProp the action changed is lost.
  • Use dispatchBrowserEvent(): it works, but it is a page-wide event, not the answer to the call you awaited. You have to add a listener before the call and remove it after. The data must be JSON, and it is written into an HTML attribute of the render.

This PR adds LiveResponse::data(). It works like the LiveResponse helpers added in 3.5: the data is sent with the render, not instead of it. So the component re-renders as usual, and the changes of the action are kept.

#[LiveAction]
public function search(ProductRepository $repository, #[LiveArg] string $query): LiveResponse
{
    $this->query = $query; // still re-rendered on the page

    return LiveResponse::data(['total' => $repository->countMatching($query)]);
}
const response = await component.action('search', { query: 'lamp' });
const data = await response.getData()?.json();
  • Arrays, scalars, null and \JsonSerializable objects are sent as JSON, with the same encoding as JsonResponse.
  • A string is sent as is, with the content type you give, so any format works: LiveResponse::data($xml, 'application/xml').
  • getData() returns a standard Response, so the data is read with json(), text(), blob() or arrayBuffer(). It returns null when the action sent no data.
  • It uses the same transport as LiveResponse::downloadFile(): the data comes after the HTML in the same body, and X-Live-Html-Length gives the split. A new X-Live-Data-Type header gives its content type.
  • The same rules apply as for the other LiveResponse helpers: POST only, never from the default action, and the last one wins in a batch.

The public API grows by one static method in PHP and one method in JavaScript.

Similar tools already offer this:

  • Livewire (Laravel): calling an action from JavaScript, for example await $wire.getPostCount(), returns the value that the PHP method returned. The component re-renders as usual (unless the action is marked #[Renderless]).
  • Phoenix LiveView: pushEvent(event, payload, (reply) => ...) receives the map returned by {:reply, map, socket} from the server, and the view is updated in the same round trip.

This PR brings the same idea to LiveComponent, in the style of the existing LiveResponse helpers.

#2967 asks for the same use case, by skipping the render when an action returns JSON. In the discussion there, the lost render was a concern, and LiveResponse helpers were suggested for this kind of feature. This PR follows that direction, and covers any format, not only JSON.

The new tests fail without the change: LiveResponse::data() does not exist, the X-Live-Data-Type header is missing, and getData() is not a function. The PHP and JavaScript test suites pass, and the documentation has a new "Sending Data to JavaScript" section next to the download responses.

@carsonbot carsonbot added Documentation Improvements or additions to documentation Feature New Feature LiveComponent Status: Needs Review Needs to be reviewed labels Sep 26, 2026
@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Packages dist files size difference

Thanks for the PR! Here is the difference in size of the packages dist files between the base branch and the PR.
Please review the changes and make sure they are expected.

FileBefore (Size / Gzip)After (Size / Gzip)
LiveComponent
live_controller.d.ts 8.11 kB / 2.11 kB 8.15 kB+1% 📈 / 2.12 kB+1% 📈
live_controller.js 95.17 kB / 21.69 kB 95.5 kB0% / 21.77 kB0%

@kbond kbond left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cool!

Question: is there an easy way, in your live action, to check if the request was a normal live component call or from custom js? Does that make sense? If custom js, return data, otherwise, do the normal thing. If I understand correctly, the normal thing always happens.

@smnandre smnandre left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(if you guys were waiting for me, I'm sorry)

This is such a great PR, @Pechynho! I remember first time you mentioned that idea/need, and I'm very happy to see it implemented that clean-ly :)

🤝

Let's rebase/add changelog (3.9) and ... LGTM 😃

@Pechynho
Pechynho force-pushed the feat-live-response-data branch from fddc11f to 7a21fc0 Compare November 24, 2026 21:01
…pt that called an action

| Q              | A
| -------------- | ---
| Bug fix?       | no
| New feature?   | yes
| Deprecations?  | no
| Documentation? | yes
| Issues         |
| License        | MIT

Calling a LiveAction from your own JavaScript with `component.action()` is documented and useful. But the action has no clean way to send a result back to the code that called it. Some examples where this is needed:

- a JavaScript widget (an autocomplete, a map, a chart) asks the component for data;
- an action saves something and the JavaScript needs the new id or a message;
- an action checks something (is this name free?) and the JavaScript shows the answer.

The component already has everything the action needs: its props, its entities, its form. Today the options are:

- **Return a `JsonResponse`:** the client does not see a component response, so it shows the error modal. The component does not re-render, so every `LiveProp` the action changed is lost.
- **Use `dispatchBrowserEvent()`:** it works, but it is a page-wide event, not the answer to the call you awaited. You have to add a listener before the call and remove it after. The data must be JSON, and it is written into an HTML attribute of the render.

This PR adds `LiveResponse::data()`. It works like the `LiveResponse` helpers added in 3.5: the data is sent **with** the render, not instead of it. So the component re-renders as usual, and the changes of the action are kept.

```php
public function search(ProductRepository $repository, #[LiveArg] string $query): LiveResponse
{
    $this->query = $query; // still re-rendered on the page

    return LiveResponse::data(['total' => $repository->countMatching($query)]);
}
```

```js
const response = await component.action('search', { query: 'lamp' });
const data = await response.getData()?.json();
```

- Arrays, scalars, `null` and `\JsonSerializable` objects are sent as JSON, with the same encoding as `JsonResponse`.
- A string is sent as is, with the content type you give, so any format works: `LiveResponse::data($xml, 'application/xml')`.
- `getData()` returns a standard `Response`, so the data is read with `json()`, `text()`, `blob()` or `arrayBuffer()`. It returns `null` when the action sent no data.
- It uses the same transport as `LiveResponse::downloadFile()`: the data comes after the HTML in the same body, and `X-Live-Html-Length` gives the split. A new `X-Live-Data-Type` header gives its content type.
- The same rules apply as for the other `LiveResponse` helpers: POST only, never from the default action, and the last one wins in a batch.

The public API grows by one static method in PHP and one method in JavaScript.

Similar tools already offer this:

- **Livewire (Laravel):** calling an action from JavaScript, for example `await $wire.getPostCount()`, returns the value that the PHP method returned. The component re-renders as usual (unless the action is marked `#[Renderless]`).
- **Phoenix LiveView:** `pushEvent(event, payload, (reply) => ...)` receives the map returned by `{:reply, map, socket}` from the server, and the view is updated in the same round trip.

This PR brings the same idea to LiveComponent, in the style of the existing `LiveResponse` helpers.

The new tests fail without the change: `LiveResponse::data()` does not exist, the `X-Live-Data-Type` header is missing, and `getData()` is not a function. The PHP and JavaScript test suites pass, and the documentation has a new "Sending Data to JavaScript" section next to the download responses.
@Pechynho
Pechynho force-pushed the feat-live-response-data branch from 7a21fc0 to 1c363cb Compare November 24, 2026 21:14
@Pechynho

Copy link
Copy Markdown
Contributor Author

Thanks @smnandre! Rebased on 3.x (resolved the conflicts with noRender() and #4272) and moved the changelog entry and the versionadded to 3.9.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Documentation Improvements or additions to documentation Feature New Feature LiveComponent Status: Reviewed Has been reviewed by a maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants