Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

311
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda