Using only native JavaScript Vanilla, Rails does not execute create.js via Ajax

Concerning Rails 4 and Vanilla JavaScript, I encountered an issue with my code for creating a Shop record via Ajax. The record is successfully created, but the create.js file is not being triggered as expected.

A strange occurrence happens in Chrome where it displays Rendered shops/create.js.erb without any action taken, while Firefox shows ActionView::MissingTemplate.

It appears that the request is being processed as HTML, which might be causing the problem.

# updated 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


# revised 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');


# Updated logs for Firefox:

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'


# Revised 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)

Answer №1

To trigger Javascript responses like create.js.erb, update.js.erb, and destroy.js.erb, you need to use Unobtrusive JavaScript (UJS). Here's what I did to make it work:

  • Enclose everything in a form tag and include remote: true to enable UJS support
  • Use the following function to submit the form:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Codeigniter failing to perform AJAX requests

After taking some code from an example and implementing it in my controller, I encountered issues with populating another dropdown using my own table. This is what my Controller looks like: class Bkp extends CI_Controller { function __construct() { ...

Different ways to showcase a value from the CSS file on the console using console.log

In this guide, you can learn how to create a custom directive in Angular by following this tutorial: Custom Directive Tutorial. The directive should function as intended. Still, I want to see the color value set in the CSS file displayed on the console us ...

Enhance your data table by updating the content without the need to refresh the entire page in CodeIgniter

Every time I update or insert data using the bootstrap modal form and ajax, the entire page reloads. Instead of refreshing the whole page, I want only the data table to be refreshed. Below is my ajax script: <script> $(document).ready(function( ...

What is the best way to initiate an onload event from a script embedded within a jquery plugin?

Currently, I am in the process of developing a jQuery plugin. One issue that I have encountered involves a script tag being dynamically added for LivePerson.com. The script is supposed to trigger an onLoad function specified in the configuration. However, ...

Is there a way to display the contents of a zipped file using an HTML IFrame?

Can I display the contents of a zipped file in an HTML iframe? For example: My_File.pdf.zip contains My_File.pdf. I currently have something like this <iframe src="/path of the folder/My_File.pdf.zip" /> The src attribute points to the zipped file ...

Using the same ng-model to show distinct values in two separate input fields

I have a form with a dropdown list that loads data using the ng-model="placeid". When a user selects an option from the dropdown, I want to display the selected place's latitude (place.lat) in an input box. Here is the dropdown list code: <select ...

What is the best way to create a delay in user hover activation before triggering a slideDown

In my current code snippet, I have implemented the functionality to perform a slideDown action when a user hovers over an element. However, I would like this slide down effect to only occur if the user has hovered for at least 2 seconds. If the user does n ...

Prevent the session from being refreshed when making an ajax call

Can CodeIgniter be configured to bypass session timeout reset if a POST request is sent via Ajax to a specific controller function? I have regular Ajax calls within the user login dashboard to monitor certain aspects, but these calls keep the session act ...

What are some strategies for navigating the constraint of having multiple root elements in Vue.js?

Seeking assistance from the experts here to solve this particular issue. I have a dataset that looks like this: [ { title: 'Header', children: [ { title: 'Paragraph', children: [], }, ], }, ...

Easily send maps and directions straight to your mobile device with mapQuest

Currently creating a web application with mapQuest integration. I have two queries: 1) Is there a way to share routes from the web app to my phone? 2) How can I track my phone device and display the route on the web app? Appreciate any assistance. PS: Us ...

HTML5 database error: Uncaught TypeError due to illegal invocation

When I test the code below in Chrome, I encounter an error: var db = openDatabase('foo', 1, 'foo', 1111); var sql = function(callback){ db.transaction(function(tx){ callback(tx.executeSql); }); }; sql(function(query){ ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

Failed jQuery AJAX request to database with no returned information

I'm really confused about where the issue lies :S The button triggers a function that passes the parameter "sex" and initiates an ajax call to ajax.php, where I execute a MySQL query to retrieve the results and populate different input boxes. When I ...

Extract data from the HTML source code in JavaScript and transfer it to a personalized JavaScript variable within Google Tag Manager

Running an e-commerce website on Prestashop and facing an issue with data layer set up. Instead of a standard data layer, the platform generates a javascript variable called MBG for Enhanced E-Commerce implementation. <script type="text/javascript"> ...

The issue with Go Code is that it fails to display the JSON data received from a jQuery

Problem Description The issue I am facing is that Go Code is not displaying the posted JSON value from jQuery AJAX. Main Go Code routing := chi.NewRouter() routing.Post("/authenticate", AuthenticateRouter) Go Code Snippet func AuthenticateRouter(w http. ...

Using jQuery, create a keypress event that functions like the tagging feature on Facebook when composing a wallpost and typing the "@" symbol

Hey everyone! I'm new to jquery and javascript, but I'm learning a lot. Currently, I'm working on replicating Facebook's user tagging feature in a wall post when the "@" symbol is input in a text area. I've already set up a functio ...

Enhance Website User Experience: Keeping Track of Scroll Position When Users Navigate Back in Browser

Have you ever experienced the frustration of scrolling through a page with infinite scroll, only to click on a link and then go back to find that you've lost your place in the scroll? You're scrolling down a lot, You click on a link from the i ...

It seems that BeautifulSoup and Selenium are unable to locate the div or text elements on the website

I have been attempting to utilize BeautifulSoup or Selenium in order to retrieve the Head to Head text or its corresponding div element on betexplorer (link provided below), but my efforts have unfortunately proved to be unsuccessful. Despite being able to ...

I am struggling to make php redirect work using onclick() function

My PHP button is not redirecting properly. Assuming the page destination is correct, is there anything else that could be causing this issue? echo "<button id=\"create\" onclick=\"location.href('/team/teams.php?op=create');&bso ...

Select specific columns from an array using Typescript

I have a collection of objects and I'm looking for a way to empower the user to choose which attributes they want to import into the database. Is there a method to map and generate a separate array containing only the selected properties for insertion ...