Updating the current view in Rails with newly fetched data

NOTE: To make it easier, skip to the EDIT part below. Thank you!

I am currently working on adding a simple feature to my app.

The feature involves a view with a chart that depends on two query parameters: :from and :to. I am using "Chartkick" and below are snippets of my view and controller.

Here is the index view along with a debug feature:

<%= params %>

<input type="text" id="from-date">
<%= column_chart dashboard_chart_path(:from => @from, :to => @to)  %>

Controller:

class DashboardController < ApplicationController
  def index
    @from = params[:from]
    @to = params[:to]
  end

  def call_from_ajax
    from = params[:from] 
    to = params[:to]
    render action: 'index', to: to, from: from
  end

end

Everything is working as expected when I manually input query parameters in the URL. The chart displays the correct data. Now, I have this JavaScript code for testing:

$(document).ready(function(){
    $('#from-date').pickadate({
      onClose: function() {
        array ={
          "from": "20-05-2018",
          "to": "01-05-2018"
        }
        $.ajax({
          type: 'GET',
          url: 'dashboard_chart_ajax',
          data: array
        })
      },
  });

Route:

get 'dashboard_chart_ajax', to: 'dashboard#call_from_ajax'

The ajax call is working correctly. The 'call_from_ajax' method is triggered, and my console confirms that the Index view has been rendered. However, the params variable in my view does not update, nor does the chart... (I verified using byebug, params does contain :from and :to values). What am I overlooking? Appreciate any assistance.

EDIT:

For practice purposes, let's consider a different scenario:

I included a new route

get 'button', to: "dashboard#test"

My controller methods

def test
  redirect_to controller: :dashboard, action: :index, from: 'start_date', to: 'end_date'
end

def index
  @from = params[:from]
  @to = params[:to]
end

And a button in the view

<%= button_to "Some Button", button_path, method: :get, remote: true %>
<%= params %>

I am aiming to have the params variable in the view updated upon clicking the button.

When I initially load the page, in the :index method I see:

<ActionController::Parameters {"controller"=>"dashboard", "action"=>"index"} permitted: false>

Upon clicking the button, I see:

<ActionController::Parameters {"from"=>"start_date", "to"=>"end_date", "controller"=>"dashboard", "action"=>"index"} permitted: false>

However, the view remains unchanged... I must be missing something crucial, as I am still learning.

My objective is to modify a variable with my 'test' method, and reflect this change in the same view.

If anyone can offer assistance, I would greatly appreciate it.

Answer №1

It appears that there could be a couple of issues at play here.

Firstly, you're not actually utilizing the AJAX response in your code. You might want to consider incorporating it like so:

$(document).ready(function(){
  $('#from-date').pickadate({
    onClose: function() {
      array ={
        "from": "20-05-2018",
        "to": "01-05-2018"
      }
      ajaxResponse = $.ajax({
        type: 'GET',
        url: 'dashboard_chart_ajax',
        data: array
      })
      ajaxResponse.success(data) {
        // perform actions with the returned data
      }
    },
});

My syntax might not be perfect as I have been coding in coffescript lately. I apologize for any errors in advance.

Secondly, the $(document).ready section could potentially cause issues, especially if you are using turbolinks. I personally prefer to remove turbolinks from my projects as I find them unnecessary. However, this is just a suggestion based on my experience.

Answer №2

When you include remote: true in your button, you're instructing Rails to make an asynchronous request instead of a traditional page refresh. This means that an Ajax call is made and the response is not automatically handled. To update the page based on this response, you have a couple of options: either remove the remote attribute to make a regular call, or attach a callback to the completion of the Ajax request. The latter option is more complex to set up but offers more flexibility and control.

If you're interested in learning how to bind callbacks to Rails UJS events, you can check out this example: https://github.com/rails/jquery-ujs/wiki/ajax

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

Automating the creation of box UVW maps through programming

I'm looking for a way to automatically create box UVW maps in 3D models, similar to the functionality of UVW Map -> Box in programs like 3ds Max. Here's an example with the default UV mapping And here is an example with the desired box UV ma ...

Tips for Drawing Lines and Preserving Them When a Condition is Met

I am currently utilizing Node.Js in an attempt to outline objects within an image based on certain conditions being met. My goal is to draw lines around specific portions of the image received from an API response. Whenever the response includes the keywor ...

Achieving success by correctly reaching the window's edge during an event (onscroll)

This happens to be my 1st inquiry. Specifically, I have a navigation menu with a transparent background and I am attempting to alter the background once it reaches the top edge of the window. window.addEventListener("scroll", navSticky); function navSt ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Transfer information from .gs (Google Apps Script) to a variable inside a <script> tag in an HTML document

[ {"id":1,"label":"Node 2"}, {"id":2,"label":"Node 3"}, {"id":3,"label":"Node 4"}, {"id":4,"label":"Node 5"} ] Hello there! The function getArray() in the code snippet above is returning the specified string ↑. I need help connecting this data w ...

Error in Express.js application: form fields lose their values

I am currently developing a blogging application using Express, EJS and MongoDB. One of the main features is an "Add New Post" form with an addPost() method in the controller; exports.addPost = (req, res, next) => { const errors = validationResult ...

In need of changing the date format post splitting

I need help converting a date from MM/DD/YY to YYYYMMDD The current code I have is giving me an incorrect output of 2211. How can I implement a check on the Month and Day values to add a leading zero when necessary? var arr = '1/1/22'; arr = NTE ...

Utilizing the state as a condition within the useEffect to update the component

Is there a way to automatically hide the mobile menu when the URL changes in ReactRouter? I have noticed that I get a warning for not tracking mobileOpen as a dependency, but strangely the code still works fine. const Navbar: React.FC<Props> = props ...

Exclude specific fields when updating a document in Firebase using the update()

Currently, I am storing a class in Firebase by using the update() function. Is there a way to stop specific fields (identified by name) of the object from being saved to the Firebase database? It's similar to how we use the transient keyword in Java ...

The functionality of my JQuery validation plugin seems off when it comes to handling checkbox inputs

I created a versatile validation plugin that accepts a function to check input validity, along with callbacks for valid and invalid cases. The plugin consists of two functions: '$.fn.validation()' to attach validation logic and success/failure ca ...

Attempt to import Recharts into React was unsuccessful

I am currently exploring the use of recharts in a React project, but I am facing difficulties when trying to import components from its library. I have added it to my package.json file as follows: "recharts": "^2.0.9", However, I am ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

Utilizing the js-yaml library to parse a YAML document

Currently, I'm utilizing js-yaml to analyze and extract the data from a yaml file in node js. The yaml file consists of key-value pairs, with some keys having values formatted like this: key : {{ val1 }} {{ val2 }} However, the parsing process enco ...

Display custom modals in React that showcase content for a brief moment before the page refreshes

I recently developed a custom modal in React. When the Open button is clicked, showModal is set to true and the modal display changes to block. Conversely, clicking the Close button sets the display to none. However, I noticed a bug where upon refreshing ...

Limiting the number of rows in pagination using a select option

Having a pagination feature on my page, I now aim to add a new functionality. When the user selects the number of rows from a drop-down menu, the webpage should display matching data. Despite trying to implement this with ajax, the limit variable is not be ...

What could be causing the never-ending page reloads on a PWA Vue application?

I'm currently working on turning my Vue app into a PWA using the Vite-PWA-plugin (this plugin) However, I've encountered an issue where the page keeps reloading repeatedly when served from cache, especially when utilizing the Oauth2 protocol for ...

React Navigation Bar Links Fail to Show Content

I'm a beginner in the world of React and I could really use some assistance. Right now, I am working on creating a portfolio using React and focusing on the Nav component. Although I haven't encountered any errors in the Console, when I click on ...

Issues with Wordpress plugins functioning properly in Internet Explorer versions 9 and above

My wordpress site is running smoothly on Chrome, Safari, and Firefox, but Internet Explorer seems to be causing some issues. I had a similar problem with two plugins across all browsers, but after disabling 'AJAX' transitions for certain pages, e ...

Persistent NW.js Local Storage Cache Remains Present even After Deleting Application

I have been encountering an issue in my NW.js app where I store data in the Local Storage. Even after deleting the app and cleaning up cache information, the Local Storage data seems to persist. When I reinstall the app, the stored data reappears as if it ...

Which specific web framework supports the functionalities of Microsoft Dynamics CRM 2011?

Is there an SDK available from Microsoft that can help me create a web product with similar rich ajax features as Microsoft Dynamics CRM 2011? I have considered using Microsoft SharePoint Foundation 2010, but I am concerned that it is designed for small o ...