Refresh the Rails HTML table with new data by incorporating ajax requests and vanilla JavaScript

I'm struggling to find a solution without using jQuery in my current scenario. How can I refresh a partial on my page without reloading the entire page?

Within my new.html.erb file, there's a button that triggers a JavaScript function each time it's clicked. This button also updates a table displaying saved data.

// new.html.erb

<div class="row">
  <div class="col-md-4"></div>
  <div class="col-md-4">
    <h1 id="countdown">10</h1>
  </div>
  <div class="col-md-4"></div>
</div>

// More HTML code

<br>

<div id="plays"><%= render 'table' %></div>

// _table.html.erb

<table class="table">
  <thead>
  <tr>
    <th scope="col">Tick</td>
    <th scope="col">Index of image in the array</td>
  </tr>
  </thead>
  <tbody>
  <% Play.all.each do |play| %>
    <tr>
      <td><%= play.current_time %></td>
      <td><%= play.image_url %></td>
    </tr>
  <% end %>
  </tbody>
</table>

// savegame.js.erb

JavaScript function contents here

My controller handles the data retrieval and model saving logic for this functionality.

// plays_controller.rb

Ruby code here

Answer №1

Modify the specified file:

// savegame.js (the .erb extension can be removed)

function saveMyGame() {
    var countdown = document.getElementById("countdown").innerHTML
    var xhr = new XMLHttpRequest();

    xhr.open('POST', '/plays/save_my_play');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
      console.log(this.responseText);
        if (xhr.status === 200) {
          document.getElementById("plays").innerHTML = this.responseText;
        }
        else if (xhr.status !== 200) {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    auth_token = document.head.querySelector("[name=csrf-token]").content;
    xhr.send(encodeURI('countdown=' + countdown + '&authenticity_token=' + auth_token));

}

Add the following view:

//

app/views/plays/save_my_play.js.erb

<%= render 'table' %>

Explanation

Once the button is clicked, the javascript function will send an AJAX request to plays/save_my_play.

Upon processing in the controller, the server will display the content of the view

app/views/plays/save_my_play.js.erb
, which includes rendering the table partial.

The function saveMyGame updates the element with id #plays using the response from the server.

Answer №2

For more information on making Ajax calls in Rails 5.1 with or without jQuery, check out this link.

Rails 5.1 now offers solid support for ajax in the ujs library.

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

Using Javascript to dynamically add an element to an array with a unique index

Given let inputArray = []; $('some_selector').each(function() { let outer, inner; outer=$(this).parent().attr('some_property'); inner=$(this).attr('a_property'); if (!inputArray[outer]) inputArray[outer] = ...

Encountered an issue when executing "npm start": The system does not recognize 'next' as a valid internal or external command

Encountering an issue when running the "npm start" command in the terminal while attempting to create a cryptocurrency tracker using React.js Displayed contents of my package.json file: { "name": "nextjs-crypto-api", "version ...

Switching views in AngularJS by using a controller to control the content displayed in the

My JavaScript web app utilizes AngularJS to simplify tasks, but I've encountered an issue. I'm trying to change views from an ng-controller using $location.path, but for some reason, the view isn't updating even though the path in the $loca ...

Measuring Euler Angles with 9-Axis Analog Sensor Data

I am trying to calculate Euler angles using analog sensor data in JavaScript. The sensor data consists of gyro, accelerometer, and magnetometer readings in three dimensions. I find the mathematical aspect a bit challenging, so any assistance or advice woul ...

Redirecting from HTTP to HTTPS with node.js/Express

Are there steps I can take to modify my web application to operate on HTTPS instead of HTTP using node.js/express? I require it to run on HTTPS due to the use of geolocation, which Chrome no longer supports unless served from a secure context like HTTPS. ...

local individuals and local residents (duplicate) dispatched from the server

Upon analyzing my server's response, I have observed a duplicate of my locals within the locals object. Here is an example: Object { settings: "4.2", env: "development", utils: true, pretty: true, _locals: { settings: ...

Guide on transferring JavaScript Objects from the Front End to Spring Boot Back-end and effectively processing and parsing them

After struggling with this issue repeatedly while developing my web apps, I've reached a breaking point and need some help. My frustration might come across as venting, but I'm genuinely stuck. The challenge I'm facing is sending key-value ...

Using XMLHttpRequest with gzip compression

Utilizing the request module in node.js makes it simple to create a request that can retrieve and correctly decompress compressed data from the source: var request = require('request'); var requestOptions = { url: 'http://whatever.com/g ...

Having trouble capturing the CHANNEL_ANSWER event in my node.js script when communicating with Freeswitch

Greetings to all! I have a query regarding freeswitch. Although my experience with freeswitch is limited, I am currently working on connecting my node js script to the freeswitch server. So far, I have managed to establish a successful connection and gene ...

Enhance your property by adding the isDirty feature

Managing changes to properties of classes in TypeScript can be optimized by tracking only the fields that have actually changed. Instead of using an array to keep track of property changes, I am exploring the idea of implementing an isDirty check. By incor ...

Date Range Selection Widget malfunctioning when used within a popup modal

Having trouble with integrating the rsuite daterangepicker and antd's daterangepicker into a React Material UI Dialog/Modal. The date picker popup seems to either not show up or appear outside of the modal window. Take a look at the image below: Clic ...

Is there a way to set a value within a jQuery function, and then invoke another function to utilize that value?

Suppose I have a function called isPercentage, which utilizes a value that is defined within the function it's being called in: isPercentage = function(){ if (value < 1){ value = value * 100; console.log(value); ...

AngularJS fails to prioritize the following element

Here is my HTML code: <div ng-app="app"> <form> <div class="form-group"> <label >Username</label> <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/> ...

How can I retrieve the path to a specific subnode using Javascript/JSON?

What is the best way to obtain a JSON path that leads to a specific child node within an object? For example: var data = { key1: { children: { key2:'value', key3:'value', key4: { ... } ...

What exactly does the symbol "++" signify in the context of jQuery and JavaScript

Throughout my observations, I have noticed people employing i++, especially within a for-loop. However, the specific purpose of ++ when used with a variable remains unclear to me. My attempts to locate documentation explaining its function have been unsuc ...

Hover over the text to disable the input element and display it as a textbox

Currently, I have a situation where I have two text boxes - when text is entered into textbox1, textbox2 becomes disabled as expected. However, my second requirement is that upon disabling textbox2, hovering over it should display the message "You can ente ...

Implement 2 new search options into the datatable plugin

Looking to enhance my existing panel by adding 2 search options: Here are the credentials you'll need: username: admin pass: Nopass1234 The additional features I want to include are: 2 search options: 1. from date 2. to date What will happen w ...

Script tags that are included within the element Vue vm is bound to can result in a template error

Here is the Laravel layout template that I am currently working with: <html lang="en"> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <link href="{{ URL::asset('css/libs.css') }}" rel="stylesheet"> ...

Using jQuery to send a GET request to the current page with specified parameters

Within my application, hosted on a PHP page, I am aiming to trigger a GET request upon selecting an option from a dropdown menu. The URL of the page is: www.mydomain.it/admin/gest-prenotazioni-piazzola.php I intend to utilize jQuery to execute this GET r ...

How can I make my webpage unselectable except for specific content within a div using CSS and JavaScript?

During a live editing session, I am looking to make only specific portions of the page selectable. Can someone provide guidance on how to disable selection for everything except within a particular div? ...