Refreshing a DIV in Rails by reloading from model using a JavaScript function

Recently, I created a page displaying the number of Widgets a customer has. Below is the view written in Haml:

#available
  = "Available widgets: #{@customer.widgets.unused.count()}"

(The "unused" scope in the model displays available widgets).

When a Customer redeems Widgets using a form with ":remote => true", some JavaScript dynamically adds a DIV to the page with animation and updates the model through the controller.

Check out the controller below:

  def redeem
    @customer = Customer.find(params[:customer_id])
    number = params[:amount].to_i
    unless @customer.widgets.unused.empty?
      number.times do
        @customer = Customer.find(params[:customer_id])
        widget = @customer.widgets.unused.first # Grab first unused pass
        widget.status = "Redeemed"
        widget.save!
      end
    else
      @pay = "true"
      # customer.widgets.new
    end
    # redirect_to @customer
  

And here's the JavaScript (js.erb):

var number = <%= params[:amount] %>;
<% if @pay.eql? "true" %>
  $("#widget-pay").modal('toggle');
<% else %>
   while (number > 0) {
     var item = $('<div class="widget-show">...</div>');
     $('#allwidgets').isotope('insert', item);
     number --;
   }
<% end %>

Now, I am facing an issue where I need to update the "#available" DIV with the new Widget count. How can this be accomplished?

Options include reloading the page to fetch data from the model again or just updating the DIV. Unfortunately, neither seems achievable directly from the JavaScript.

Answer №1

If you want to achieve this functionality, try the following approach:

render :js => "$('#available').append(widget)"
widget.save!

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

Execute controller action upon item selection within KODataTable MVC table

I am displaying data in a table using AJAX to call an Action that returns a JSON list. Output: I want each user (row in the table) to be clickable and linkable to an edit page (Admin/Edit/Id). This can be done either by clicking on them or by having an E ...

Error: Attempting to access the 'map' property of an undefined variable, cart

My project consists of two main components, App.js and Cart.js. I am utilizing material-ui and commerce.js API for this application. import React , {useState , useEffect} from 'react' import Products from './Components/Products/Products&apos ...

How to implement a select all feature using React and MaterialUI

I am facing a challenge with managing multiple sets of checkboxes independently along with a toggle that can switch them all on or off within their respective groups. Each checkbox has two states, and I can identify the checkbox being clicked using event.t ...

Searching for elements by tag name in JavaScript

Recently, I attempted to create JavaScript code that would highlight an element when a user hovers their cursor over it. My approach involves adding an event listener to every child within the first "nav" tag in the current document: let navigation = docum ...

Lighthouse Issue: Facing PWA Challenges with a "Request Blocked by DevTools" Error

For hours now, I've been struggling to make Lighthouse work in Chrome for my initial PWA project. I feel completely lost as nothing seems to be making sense despite the basic code I have included below. The issue arises when I load the page normally ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

What is the best way to extract the value associated with the "first_name" key in the given object?

What is the best way to extract the value associated with the first_name key from the object below? { "first_name": "D", "last_name": "N", "phone_number": 1233414234 } ...

An issue with Rails 3 ajax call resulting in ActionView::MissingTemplate error

Currently, I am attempting to perform an ajax call without needing to return any data, or maybe just return a 200 status code. The error I encountered is: ActionView::MissingTemplate (Missing template .... Within the controller, this is my ajax method: ...

Having trouble with NextJS not updating state upon button click?

I am encountering a problem with my NextJS application. I am attempting to show a loading spinner on a button when it is used for user login. I have tried setting the `loading` state to true before calling the login function and then reverting it to fals ...

Express.js never terminates a session

I have a Backbone View that makes an Ajax call to the server to delete a session. Upon triggering the following event on the server: app.delete('/session', function(req, res) { if (req.session) { req.session.destroy(function() { ...

The error message "node-soap - callback is not a function" is indicating that there

Encountering a common TypeScript error while calling a SOAP method on a node-soap client in NodeJS. Seeking guidance on resolving this issue. https://www.npmjs.com/package/soap - version: 0.35.0 Sample Code Snippet const [result] = await mySoapClient.Per ...

The challenges of $location.search().name and base href in application URLs

I am working on an Angular app and my URL appears as http://localhost:8080/personal?name=xyz. To extract the 'xyz' value in JavaScript, I am using $location.search().name. Here is a snippet of my code: app.js app.config(function ($locationProv ...

Could the quantity of JavaScript files impact the performance of a project and cause any delays?

In my current HTML and JavaScript project, I am incorporating multiple JavaScript files. I'm curious to learn about the potential impact of having numerous JavaScript files on a web project's efficiency and speed. Can anyone shed some light on th ...

Guide to generating customized CSS styles on-the-fly in Vue (similar to Angular's dynamic styling capabilities)

When working with Angular, we have the capability to dynamically set CSS properties. For example: <style ng-if="color"> .theme-color { color: {{color}}; } .theme-background-color { background-color: {{color}}; } .theme-border-color { border-color: { ...

Steps for eliminating QRcode warning in npmjs package

Issue: Warning Message (node:24688) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) Seeking Solution: How can I prevent this warning ...

The function persists in outputting a true result, despite the fact that it is expected to output

Currently, I am working on a NextJS project where I have a client-side form. I've been attempting to implement validation for the form by creating a separate function called validateForm(). However, no matter what input is provided, the function alway ...

How to directly stream a Google Cloud Storage file into an fs.Readstream without the need to save it

Is there a way for me to send a video file directly from Google Cloud Storage to an API that only accepts fs filestreams without having to download and save the file locally first? I'm currently using the code below to send video files, but it require ...

Navigating through parent folder HTML files from child folder HTML files

Seeking guidance as I embark on a new project! Check out this link to see my skills in action: collegewebsite.zip Now for the query at hand. I am working on a project named Coffee Cafe for my tuition assignment. It involves utilizing CSS and HTML with J ...

My JavaScript if-else statement isn't functioning properly

I'm facing an issue with my if statement not functioning correctly when trying to validate non-numeric inputs for the weight variable upon submission. What could be causing this problem? submitBtn.onclick = function(){ var name = document.get ...

Add a new key-value pair to the mock data by clicking on it

Hey there! I'm currently tackling a task that involves toggling the value of a boolean and then appending a new key-value pair on click. I've been attempting to use the . operator to add the new key-value pair, but it keeps throwing an error. In ...