0

Using Rails 4 and native Javascript (Vanilla). I have the following code to create a Shop record via Ajax. The record creates successfully, but refuses to fire create.js correctly.

Weird behavior is that on Chrome it says Rendered shops/create.js.erb but done nothing, but on Firefox, it says ActionView::MissingTemplate.

I also notice that the request is processed as HTML, if that's the issue.

# shops_controller.rb
class ShopsController < ApplicationController
  def create
    @day_id = params[:day_id]
    shop_details = JSON.parse(shop_params[:shop]).with_indifferent_access
    @shop = Shop.find_or_create_by(source_id: shop_details[:shop_id])
    @shop.save
  end

  private

  def shop_params
    params.permit(
      :shop,
      :day_id
    )
  end
end


# global.js
function addShop(dayId, shop) {
  var shopJSON = encodeURIComponent(JSON.stringify(shop));
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/shops", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  xhr.setRequestHeader("X-CSRF-Token", CSRF.token());
  xhr.send("shop=" + shopJSON + "&day_id=" + dayId);

  xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE ) {
      if (xhr.status != 200) {
        alert('not ok');
      }
    }
  };
}

# app/views/shops/create.js.erb
alert('good');


# Firefox Log

Started POST "/shops" for 127.0.0.1 at 2017-01-08 13:11:36 +0800
Processing by shopsController#create as HTML
  Parameters: {"shop"=>"...", "day_id"=>"85"}
  Shop Load (0.4ms)  SELECT  `shops`.* FROM `shops` WHERE `shops`.`source_id` = 'ChIJHbeh32U6K4cR-lP5hY96smc' LIMIT 1
   (0.2ms)  BEGIN
  SQL (3.6ms)  INSERT INTO `shops` (`source_id`, `created_at`, `updated_at`) VALUES ('...', '2017-01-08 05:11:36', '2017-01-08 05:11:36')
   (0.8ms)  COMMIT
   (0.2ms)  BEGIN
   (0.2ms)  COMMIT
Completed 500 Internal Server Error in 34ms (ActiveRecord: 8.1ms)

ActionView::MissingTemplate (Missing template shops/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/Users/abc/Sites/powerapp/app/views"
  * "/Users/abc/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/devise-4.2.0/app/views"
):
  actionview (4.2.6) lib/action_view/path_set.rb:46:in `find'


# Chrome Log:
Started POST "/shops" for 127.0.0.1 at 2017-01-08 13:13:08 +0800
Processing by shopsController#create as */*
  Parameters: {"shop"=>"...", "day_id"=>"79"}
  Shop Load (0.3ms)  SELECT  `shops`.* FROM `shops` WHERE `shops`.`source_id` = 'ChIJASFVO5VoAIkRGJbQtRWxD7w' LIMIT 1
   (0.2ms)  BEGIN
  SQL (9.2ms)  INSERT INTO `shops` (`source_id`, `created_at`, `updated_at`) VALUES ('...', '2017-01-08 05:13:08', '2017-01-08 05:13:08')
   (0.6ms)  COMMIT
   (0.2ms)  BEGIN
   (0.2ms)  COMMIT
  Rendered shops/create.js.erb (0.8ms)
Completed 200 OK in 44ms (Views: 25.1ms | ActiveRecord: 10.7ms)

1 Answer 1

1

Action type Javascript response such as create.js.erb, update.js.erb, destroy.js.erb only works with UJS. Here's what I modified to get it working:

  • Wrap everything in a form, and add remote: true to get UJS support
  • Submit form using the following function:

// native Javascript Vanilla
function ujsSubmit(form) {
  var event = document.createEvent("HTMLEvents");
  event.initEvent("submit", true, false);
  form.dispatchEvent(event);
}

// jQuery
$(form).trigger("submit");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.