Debug School

rakesh kumar
rakesh kumar

Posted on

How to dispatch client side component to server side in live wire

Step1: define the function in javascript

updateSelectedString() {
    console.log("selectionChanged");

    // This should collect all selected values as an array
    this.selectedString = this.selected.map(item => item.value);
    console.log(this.selectedString);  // Log the array to ensure all selected items are included

    // Send the array as a JSON string
    Livewire.dispatch('selectionChanged', this.selectedString);
}
Enter fullscreen mode Exit fullscreen mode

This uses Livewire's dispatch method to send the selectionChanged event along with the array of selected values (this.selectedString). The values are sent as a JSON string

Listener Setup

protected $listeners = ['updateProperty', 'selectionChanged' => 'updateSelectedSites'];
Enter fullscreen mode Exit fullscreen mode
  1. $listeners is a property in a Livewire component that registers event listeners.
  2. selectionChanged is an event that triggers the updateSelectedSites method.
  3. updateProperty is another event listener, but it's not detailed here . Define function in livewire server side
public function updateSelectedSites($selectedValues)
{
    Log::info("updateSelectedSites xcvxc");
    Log::info("Processed array:", ['data' => $selectedValues]);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)