Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!