Using Rails to render a partial with a JSON object

In my rails app, there is a javascript callback that runs after a post is created. This callback polls a processing endpoint to check if an image has finished processing and then updates the view accordingly:

create.js.erb create callback

// initiating the poll for processed image
function imageProcessed() {
  $.ajax({ url: "/posts/" + <%= @post.id %> + "/processing"})
    .done(function(data) {
      if (data.processing) {
        setTimeout(imageProcessed(), 2000);
      } else {
        // displaying the processed image url
        $("#js-capture-container").html('<img src="' + data.image_url + '" alt="image">');
      }
    });
}

imageProcessed();

posts_controller.rb endpoint

def processing
  data = { processing: @post.image_processing }
  if <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="46670636293532682f2b272123">[email protected]</a>_processing?
    data[:image_url] = @post.image_url(:pair)
  end
  render json: data

The current setup works well, but I am interested in taking the data received in the ajax call and rendering an existing _post.html.erb partial with this data.

I am looking for a way to return an updated instance of @post and then render that object into the partial.

"<%= escape_javascript(render @post) %>"
in create.js.erb

Any suggestions or ideas would be greatly appreciated. Thank you!

Answer №1

I successfully managed to make it function by including the partial as an HTML string within the json object, following a similar approach to the one highlighted in this post: Rails 3 - Rendering a PARTIAL as JSON

I modified the if condition in post_controller.rb to:

if <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a584e5d5cad6d18bccc8c4c2c0">[email protected]</a>_processing?
  data[:partial] = render_to_string(@post)
end

and then in create.js.erb, I updated the callback to:

$("#js-capture-container").html(data.partial);

It was a neat and elegant solution.

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

Error encountered while attempting to validate JWT

This question has been asked multiple times, but I'm still struggling to find the root cause of the issue. I have already signed some data with a token, but when I attempt to verify it, I receive an error message saying "jwt malformed". Interestingly, ...

Executing Angular CLI tasks using a script file rather than directly from the CLI? Embracing the power of Localization and Internationalization

Our Angular 2 app is gearing up for internationalization/localization, and I am looking to create scripts that can handle tasks such as generating translation source files or building/serving the application with translations in a specific language. Inste ...

Ways to incorporate react suspense with redux toolkit

I am currently using Redux toolkit to display data from an API, and I want to show the user a "loading data..." message or a spinner before displaying the city information. I have been attempting to use React Suspense, but it doesn't seem to be worki ...

Executing Promises in an Array through JavaScript

LIVE DEMO Here is a function provided: function isGood(number) { var defer = $q.defer(); $timeout(function() { if (<some condition on number>) { defer.resolve(); } else { defer.reject(); } }, 100); return defer.pro ...

Is memory allocated for 32 bits for variables with an undefined value in Javascript?

If I have a function with the signature below: function test(variable1, variable2) {} And I call it with only one parameter: test(5); Then within the test function, variable2 will be created but with a value of undefined. I'm interested to know if ...

Is Javascript necessary for submitting a form to a PHP script?

In my current project, I am working on a page to edit information in a database. While I know how to create the form in HTML and the PHP script that runs on the server, I am facing a challenge with JavaScript. My understanding of JavaScript is limited, and ...

What is the process for adding information to datatables using jQuery?

I have been struggling to make a data table in jQuery function correctly. I am able to append data to the table, but the sorting, pagination, and search features are not working. Even though the data is visible in the table, it shows as 0 records. I am wor ...

Choosing comparable choices from the drop-down menu

I am working on a dropdown menu that contains different options. I need to use jQuery to automatically select the option that corresponds to the branch of the currently logged in user. However, when some option text is very similar, it causes an issue. // ...

Ways to create distinct identifiers within a recurring function:

I am using this function twice: function (data) { $.each(data.items, function(i,item) { var $items = $('<div class="col-sm-4 grid-item"><div class="thumbnail"><input type="checkbox" name="thing_'+i+'" ...

Shifting attention from one input to another by utilizing a barcode scanner

Utilizing a barcode scanner, I am inputting data into the fields of a webpage. The form is set up with autofocus on the initial input field. However, upon entering the first barcode in the opening field, the focus should shift to the following input field. ...

"Utilizing jQuery to Send POST Requests on Rails - Dealing

Currently, I am running a JavaScript game from file:// and attempting to send a post request to a localhost Rails server in order to add a new high score. In my JavaScript: highScoresEntryView.keyHandlers = function() { var that = this; this.pa ...

Tips on incorporating a fresh item into a expansive tree view using a recurring function or action - specifically geared towards the MUI React JS Tree View component

I am looking to implement a function or action that allows for the dynamic addition of new items to a tree view in MUI. The goal is to be able to click on a tree item and have it add another item, repeating this process as needed. <TreeView ...

Tips for activating and setting up Bootstrap popovers

I've been trying to add some popovers to my webpage, but I'm facing a hurdle. I added a few button popovers in the footer, but nothing happens when they're clicked. I created a js file for initialization and imported it at the end of my pa ...

Display sub-objects within Chart.js

I'm currently tackling a project in Ionic 3 where I am utilizing an API that returns a JSON response with nested objects. My goal is to display certain aspects of these objects within a bar graph using chart.js. Unfortunately, I lack experience in ma ...

Issue with MUI DataGridPro failing to sort the email field

I am facing an issue with the sorting functionality in the email field while creating a table using MUI DataGridPro. The sorting works fine for all other fields except for the email field. Adding some random text here to ensure my question is published. Pl ...

Why is jQuery not defined in Browserify?

Dealing with this manually is becoming quite a hassle! I imported bootstrap dropdown.js and at the end of the function, there's }($); Within my shim, I specified jquery as a dependency 'bootstrap': { "exports": 'bootstrap', ...

On screens with smaller dimensions, the divs intersect with each other

I have a project where I need to style each letter in its own box, arranged next to each other or in multiple rows with spacing between them. Everything looks great until I resize the screen to a smaller size or check it on mobile - then the letters in the ...

React transmits an incorrect argument through the function

Having a bit of trouble passing a parameter alongside the function in my for loop to create SVG paths. The props are working fine with the correct 'i' value except for selectRegion(i) which ends up getting the final value of 'i' after t ...

React BrowserRouter causing issues with "invalid hook calls"

Just starting out with React and I am working on setting up paths using BrowserRouter, Route, and Routes in my code. import React from "react" import "./App.css"; import { BrowserRouter as Router, Route, Routes } from 'react-router ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...