'Laravel livewire display session message with javascript
I am trying to submit a contact form using laravel livewire like:
public $name;
public $email;
public $phone;
public $message;
public function submitForm()
{
$attributes['name'] = $this->name;
$attributes['email'] = $this->email;
$attributes['phone'] = $this->phone;
$attributes['message'] = $this->message;
\App\Models\ContactForm::create($attributes);
$this->resetForm();
session()->flash('success', 'Your message has been sent successfully!');
$this->emit('formSubmitted');
}
Now I want to display the success message using JS on my front-end so I am doing it like this:
<script type="text/javascript">
$( document ).on("DOMContentLoaded", () => {
Livewire.on('formSubmitted', message => {
console.log('{{ session('success') }}');
});
});
</script>
The problem is that in console I am getting "empty string" instead of the session message, but when I write some static data in console.log() it gets printed in console, means that the event is being fired from the component and the response is being triggered but the session data is not being passed in the script
Also when I print the session message in blade like:
{{ session('success') }}
it gets printed properly. Can someone help me out?
Solution 1:[1]
there is no need to save the message in the session's flash, you can do as follow, dispatch a browser event from the livewire component with the message and listen to it in the front-end
$this->dispatchBrowserEvent('formSubmitted',['success' => 'Your message has been sent successfully!']);
and then listen to it in javascript
$( document ).on("DOMContentLoaded", () => {
// message is argument which is passed to closure, normally we pass as
// event
Livewire.on('formSubmitted', message => {
console.log(message.detail.success);
});
});
for a detailed view visit Livewire official Dispatching Browser Events
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
