Loc Nguyen
Loc Nguyen

Reputation: 13

respond_to do |format| format.js not working in rails 6.1.3

application.js

require("@rails/ujs").start()
require("turbolinks").start();
require("@rails/activestorage").start();
require("channels");


require("bootstrap");
require("jquery");
require('popper.js');
require("channels/jquery.nice-select.min.js");
require("channels/owl.carousel.min.js");

require("@fortawesome/fontawesome-free");

contacts_conttroller.rb

class ContactsController < ApplicationController

  def index
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(contact_params)

     respond_to do |format|
  
     if @contact.save
       ContactMailer.with(contact: @contact).notification.deliver_now
        format.html {redirect_to contacts_path}
        format.js {  }
    
     else 
      format.html {render :index}
      format.json {render json: @contact.errors, status: :unprocessable_entity}
    end
  end
end

private ##

 def contact_params
   params.require(:contact).permit(:name, :phone_number, :message, :email)
 end
end

because i want to try to see if format.js will run so it's only 1 line

create.js.erb

console.log('sending alert!');

index.html.haml

.main_contact_inner 
  = form_for @contact , url: contacts_path do |f|
    - if @contact.errors.any?
      %ul 
        - @contact.errors.full_messages.each do |msg|
          %li= msg 
    #contactForm.row.contact_form
      .form-group.col-md-4
        = f.text_field :name, class: 'form-control', placeholder: 'Tên' 
      .form-group.col-md-4
        = f.text_field :phone_number, class: 'form-control', placeholder: 'Số Điện Thoại'
      .form-group.col-md-4
        = f.text_field :email, class: 'form-control', placeholder: 'Email'
      .form-group.col-md-12
        = f.text_area :message, class: 'form-control', placeholder: 'Tin nhắn', rows: 1
      .form-group.col-md-12
        %button.btn.submit_btn.red.form-control{:type => "submit", :value => "submit"} Gửi đi

After creating the contact, no log is displayed on the console.

I don't know why my code can't go into format.js, can anyone help me with this problem?

or can someone show me how to create an alert like sweetalert2 without using controller .

Upvotes: 1

Views: 1435

Answers (2)

Njunu-sk
Njunu-sk

Reputation: 11

From rails guide

<%= form_with(model: @article, id: "new-article", local: false) do |form| %>
  
<% end %>

Add local: false

Upvotes: 1

Joel Blum
Joel Blum

Reputation: 7878

I think you are missing remote: true

= form_for @contact , url: contacts_path, remote: true do |f|

From the documentation:

:remote - if set to true, will allow Unobtrusive Javascript drivers to control the submit behavior

This is what adds the js header to the request and allows the rails controller to respond with the js format.

Upvotes: 2

Related Questions