Executing numerous Ajax requests within a single Rails view

Two ajax requests are being used on a single page, one showcasing a date and the other displaying a calendar.

The first request updates the date upon clicking a date on the calendar.

The second request allows for switching between months on the calendar.

The issue is that both functions are in index.js.erb, causing both to execute simultaneously and resetting the date in the first request whenever the month is changed.

Is there a way to have only one function from index.js.erb execute at a time?

Index.js.erb

$("#calendar").html("<%= escape_javascript(render('layouts/calendar')) %>");
$("#today").html("<%= escape_javascript(render('layouts/today')) %>");

_today.html.erb

<div class="span3 offset2 dateToday">
    <% end %>
    <span id="currentdate">
        <%= @eventDate.strftime("%B") %><br>
        <span id="dayDate"><%= h @eventDate.day %></span>
    </span>
</div>

_calendar.html.erb

  <h2 id="month">
      <span class="pull-left"><%= link_to "<", :month => (@date.beginning_of_month-1).strftime("%Y-%m-01") %></span>
      <%= h @date.strftime("%B %Y") %>
      <span class="pull-right"><%= link_to ">", :month => (@date.end_of_month+1).strftime("%Y-%m-01") %></span>
  </h2>
  <%= calendar_for(@events, :year => @date.year, :month => @date.month) do |t| %>
      <%= t.head('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') %>
      <%= t.day(:day_method => :eventdate) do |date, events| %>
  <div class="day">
      <%= link_to(date.day,  {:day => date }, :remote => true, :class => "btn dayBtn") %>      
  </div>
  <% end %>

EDIT: routes.rb

resources :calendar

root :to => "calendar#index"

match '/faq',   to: 'calendar#faq'
match ':controller/:action'

EDIT - link to ajax action

<%= link_to "<", :month => (@date.beginning_of_month-1).strftime("%Y-%m-01"), :action => "update_calendar", :remote => true %>

Thank you!

Answer №1

If you want to handle different responses based on certain parameters, you'll need to implement some logic or split them into separate actions. These actions are distinct from each other.

For example, if you choose the parameter approach:

-if param[:one]
  $("#calendar").html("<%= escape_javascript(render('layouts/calendar')) %>");
-if param[:two]
  $("#today").html("<%= escape_javascript(render('layouts/today')) %>");

Alternatively, you can separate them into distinct actions as mentioned earlier. In your controller:

def update_today
 #your today logic currently in your action
 respond_to do |format|
   format.js{render}
 end
end

def update_calendar
 #your calendar logic currently in your action
 respond_to do |format|
   format.js{render}
 end
end

Don't forget to add routes for these two actions.

In update_today.js.erb:

$("#today").html("<%= escape_javascript(render('layouts/today')) %>");

In update_calendar.js.erb:

$("#calendar").html("<%= escape_javascript(render('layouts/calendar')) %>");

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

Questions and confusion surrounding Ajax with Jquery

What is the purpose of including jquery.mn.js file in the SCRIPT tag for form validation and other jquery and ajax applications? Is there a specific location to download this file, and where should it be saved on a personal computer? ...

Vue JS Issue: Button click does not trigger tooltip update

I am currently utilizing Vue 3 alongside Bootstrap 5.2. In my project, I have successfully implemented a tooltip by the following method: App.vue <script> import { Tooltip } from "bootstrap"; export default { mounted() { Array.from( ...

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 ...

Ways to rearrange div elements using JavaScript

I need assistance with reordering div elements using JavaScript, as I am unsure of how to accomplish this task. Specifically, I have two divs implemented in HTML, and I would like the div with id="navigation" to appear after the div with class="row subhea ...

JavaScript Loading Screen - Issues with window.onload functionality

I am currently working on creating a loading screen for my project. I need to use JavaScript to remove the CSS property "Display: none" from the page, but for some reason, my code is not functioning as expected. The Issue: I discovered that using window. ...

Is there a way to make my red div switch its background color from red to green when I press the swap button?

How can I make the red div change its background color to toggle between red and green when I click on the swap button in the following code? $(document).ready(onReady); var numberOfClicks = 0; function onReady() { console.log('inside on ready ...

What could be causing the "10 $digest error" to appear in my code?

My goal was to create a basic app that could detect the size of the browser and display it. But, I encountered an error message saying "Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!" app.controller('AppCtrl',function($win ...

Determine the quantity of items currently in an active state

I created a function that toggles the active state of list items when clicked: React toggleActive: function(item){ item.active = !item.active; }, JSX <li key={property.id} onClick={() => this.toggleActive(property)}> Is there a way to count ...

How can you transfer array elements to a new array using JavaScript?

I have a task to transform the fields of an array received from one server so that they can be understood by another server for upload. My approach involves first retrieving and displaying the original field names from the initial server's array to al ...

Ways to create a shorter upper line compared to the lower line (inside a div)

I'm dealing with an unordered list that has 3 list items, each represented by a green box containing an image and 3 divs (title, location, price). My main focus is on the title div of each box. If the title is long enough to span 2 lines, I need the ...

express has a req.body that is devoid of any content

When making a request to my local server in my React app, the code looks like this: fetch("http://localhost:4000/signup", { method: "POST", mode: "no-cors", body: JSON.stringify({ name: "Joe", lname: "Doe& ...

What is the best way to share specific links on LinkedIn articles?

When the LinkedIn button is clicked, the entire link does not get passed when the image is clicked. However, the Facebook link works perfectly fine. The LinkedIn button used to work before, has anything changed since then? <div align="center"> < ...

Combining JWT authentication with access control lists: a comprehensive guide

I have successfully integrated passport with a JWT strategy, and it is functioning well. My jwt-protected routes are structured like this... app.get('/thingThatRequiresLogin/:id', passport.authenticate('jwt', { session: false }), thing ...

Delete an item from an array when a dropdown selection is made

When dealing with Angular 8, I encountered a logic issue. There are two drop-down menus: First Drop-down The options in the first menu are populated from an array of objects Example Code, ts: {rs_id: "a5f100d5-bc88-4456-b507-1161575f8819", ...

The PHP script receives an empty string value passed from JavaScript

I am struggling to pass a string from my JavaScript code to my PHP code. Here is the code snippet that triggers when I hit Enter in a text input: $('#user').keypress(function(e) { if(e.which == 13) { var val = $(this).val(); ...

The journey of data starting from a PHP file, moving through JavaScript, and circling back to PHP

I've encountered an interesting challenge with my PHP file and Wordpress shortcode. It all starts when the shortcode is embedded in a webpage, triggering a php function from within the file. This function executes an SQL query to extract data, then s ...

Identifying and capturing changes in child scope events or properties in Angular

I am encountering an issue with my form directive where I need to intercept ng-click events nested within varying child scopes of the form element. However, I am struggling to hook into these events or child scope properties in a generic way. For demonstr ...

Ways to incorporate External JS and CSS files into Angular 5 (loading files with a delay)

I have encountered some challenges while attempting to import external JS and CSS files into my Angular 5 application. Below is the code snippet that I have tried so far: Component.ts : ngOnInit() { this.loadScript(); // also attempted with ...

Having trouble loading a JSON object into a Datatable using Jquery?

I am currently utilizing DataTables in combination with Jquery. I have a data source in the form of an JSON object that I intend to retrieve via Ajax and showcase within the table. The JSON data is retrieved from the /live/log url and has the following fo ...

File in Node JS appears to be empty upon reading

My goal is to track the location of tweets in separate JSON files for each Twitter ID I monitor. The code snippet below is executed for every tweet, creating a new JSON file for each unique ID and appending the location data: console.log("@ " + tweet.user. ...