Tracking progress in a Rails job using Coffeescript

Recently, I came across a helpful gem called this gem, which allows for the seamless integration of bootstrap progress bars and the delayed job gem. The example provided by the creator uses .haml files, but since my project utilizes erb and coffeescript, I attempted to replicate his approach.

Here is a snippet from my controller:

def export
    @job = Delayed::Job.enqueue StandingsJob.new
end

This is what I have in the routes.rb file:

get 'export', to: 'scraper#export'

And this is how my home.erb.html looks like:

<%= link_to 'export', export_path, {id:'mario', remote: true} %>

<div class="progress">
  <div class="progress-bar progress-bar-striped active" role="progressbar"
       aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
    0%
  </div>
</div>

Additionally, here's a snippet from my coffeescript file:

$(document).on "turbolinks:load", ->
    $('#mario').on 'click', ->
      alert('hocliccatoooo')
      interval = setInterval( ->
        $.ajax(
          url: '/progress-job/' **** What should I add here?????****,
          success: (job) ->
            console.log('loool')
            stage
            progress
            if job.last_error != null
              $('.progress-status').addClass('text-danger').text(job.progress_stage);
              $('.progress-bar').addClass('progress-bar-danger');
              $('.progress').removeClass('active');
              clearInterval(interval);

            if job.progress_stage != null
                stage = job.progress_stage
                progress = job.progress_current / job.progress_max * 100
            else
              progress = 0
              stage = 'Uploading file?'

            if progress != 0
              $('.progress-bar').css('width', progress + '%').text(progress + '%')
            $('.progress-status').text(stage);
          error: ->
            alert('errore')
            $('.progress').removeClass('active');
            $('.progress-bar').css('width', '100%').text('100%');
            $('.progress-status').text('Finito!!!');
            clearInterval(interval);

        )
      , 100)

While the code functions correctly upon clicking the link, I'm facing an issue figuring out how to pass the ID of the job created in the controller action to the coffeescript file. Any suggestions would be greatly appreciated!

[EDIT]

This is what I have in the job class:

class StandingsJob < ProgressJob::Base

  def perform
    update_stage 'Faccio cose'
    update_progress_max 10
    for i in [0..10]
      sleep(2)
      update_progress
    end
  end
end

Upon further investigation, it appears that the perform method of my job is not being triggered (I added a puts 'lol' statement but never saw the output in the console).

Answer №1

interval = setInterval( -> var paramJob = '<%[email protected]_json%>'; // retrieving @job parameter ->

//replace SYM with "&" + "quot;" in the string

var jobObj = JSON.parse(('{' + paramJob.slice(paramJob.indexOf("SYMid"), paramJob.length)).replace(/SYM/g, '"'));//Processing the parameters

//in the ajax use jobObj.id url: '/progress-job/' + jobObj.id,

hope this explanation aids you!

Answer №2

The issue at hand here is the difference between client side and server side processing.

To resolve this, you need to assign the job-id to a data-attribute within the HTML tag during the server side rendering process. This data should be stored in the @job variable within your controller action.

After the page has been rendered and you have transitioned to the client side coffeescript code, you can extract and utilize this attribute as needed. Here is information on how to accomplish this task.

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

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Utilize Vue.js functions within data through the Vue.js context

I'm trying to incorporate a function as a data property. While it works for the 'works' data property, I need access to the this context within the function in order to calculate values from the shoppingCart property. Is there a way to achie ...

Error encountered in Chrome while trying to fetch Next.js PWA with the use of next-pwa: Unhandled TypeError

Hello, I was recently working on a Next.js project and attempted to convert it into a PWA using next-pwa. To start off, I created the next.config.js file. const withPWA = require('next- pwa'); module.exports = withPWA({ pwa: { dest: ...

Strange behavior observed with Nuxt Js asyncData method returning values

Currently, I am engaged in a project using nuxt js/vue js. The project requires me to interact with multiple REST APIs. To accomplish this task, I am utilizing the asyncData() function provided by nuxt js to make the API calls within the page component. i ...

How to use PHP and JavaScript to update a location marker on Google Maps

I'm new to web development and in need of some help, please. I have a code that is supposed to update the marker location with coordinates retrieved from a database. <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AP ...

material-ui DropDown with an image displayed for the selected value

Can someone help me figure out how to display an image in my material-ui dropdown menu? I'm currently using version 0.19.1 and have written the following code: <DropDownMenu autoWidth style={{ width: 500, marginBottom: 30 }} underlin ...

Tips for utilizing component-specific sass files with Next.js

Having a background in React, my preference is to use SCSS files at the component level just like I did in my React app. However, I encountered an issue when trying to do so in Next.js: Global CSS cannot be imported from files other than your Custom < ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

Node.js Express.js Module for Asynchronous SqLite Operations

Currently, I am working on a task that involves making synchronous requests to a database and passing the data to Express. Here is the code snippet: app.get('/', (req, res) => { let db = new sqlite3.Database('./Problems.db'); ...

Using jQuery's $.ajax() function to make an asynchronous request, and then passing the

I'm currently utilizing the jQuery $.ajax() function within a parent function that passes values into the ajax call. I am looking to have a custom callback function that can access the data parameter returned from the success function of the ajax call ...

Refreshing a webpage to accurately display changes made in a CRUD application without the need for a hard reset

My to-do app is almost fully functional - I can create items, mark them as completed, and delete them using a delete button. However, there's one issue: when I delete an item, the page doesn't update in real-time. I have to manually refresh the p ...

Whenever I navigate to a new page in my NEXTJS project, it loads an excessive number of modules

I am currently working on a small Next.js project and facing an issue where the initial load time is excessively long. Whenever I click on a link to navigate to a page like home/product/[slug], it takes around 12 seconds to load due to compiling over 2000 ...

Grab a parameter from the URL and insert it into an element before smoothly scrolling down to that

On a button, I have a URL that looks like this: www.mywebsite.com/infopage?scrollTo=section-header&#tab3 After clicking the button, it takes me to the URL above and opens up the tab labeled tab3, just as expected. However, I would like it to direct m ...

`A dynamically captivating banner featuring animated visuals created with JQuery`

I am currently in the process of designing a banner for the top of my webpage, but I have yet to come across any code that meets all my requirements. To provide clarification, I have attached an illustration showcasing what I am aiming to achieve. 1) The ...

The property 'caseSensitive' is undefined and cannot be read

After creating a simple code, I am puzzled by an error message that seems to be case sensitive. However, the code appears correct based on my understanding. Here is the code snippet: App.js const express = require('express'); const path = requir ...

Mastering the use of expressions in ng-click and ng-show in AngularJS

I've been working on creating expandable rows within a table, but I'm encountering some issues. Despite not receiving any error messages, the functionality isn't behaving as expected. I suspect there might be an issue with how I'm using ...

After updating React and Next.js to the latest versions, encountering a re-hydration error when refreshing a page? Looking for possible solutions to resolve this issue?

Encountered an unexpected Runtime Error Error: The hydration process failed because the initial UI does not align with the server-rendered content <div> <p> Gender : <span >{gender}</sp ...

Transform js into a more dynamic format to avoid redundancy when displaying items upon click

I came across a simple lightbox code snippet, but it's based on IDs and I plan to use it for more than 20 items. I don't want to manually write out 20 JavaScript lines when there could be a more efficient way to handle it dynamically. My JS skill ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...