Looking to show the contents of a Rails AJAX JSON response in your application? Having trouble with Javascript displaying [object HTMLDocument] instead? Let

I have been working on a Rails application where I implemented an AJAX / JSON controller to facilitate dynamic HTML updates within the view. For guidance, I referred to this helpful resource:

When making a call like this:

../related.json?vendor_id=1&budget_id=1
, the raw HTML partial required for updating (consisting of multiple table rows) is returned.

The call in question looks something like this:

    Rails.ajax({
      url: url,
      type: 'GET',
      success: function(data) { 
        document.getElementById("related").innerHTML = "data"
//        alert(data)
      }
    })

Upon manually inspecting the JSON request in the browser, the expected HTML output is observed. However, when attempting to replace the HTML content or even displaying the data in a test alert, the response received is [object HTMLDocument]. Following the guide I referenced, using data.html to populate the innerHTML did not yield the desired result. This issue could potentially be related to UJS / JQuery functionalities.

How can I successfully update that DOM element with the raw text obtained from the JSON call?

Answer №1

If you want to transform plain text into HTML format, you can utilize the JSON.stringify function like this:

document.getElementById("related").innerHTML = JSON.stringify(data)

Answer №2

After doing some research, I decided to make a change in my controller:

format.json { render  partial: 'related' } 

rather than

format.json { render html: render_to_string( partial: 'related' ) } 

This adjustment solved the issue - it turns out that I was providing incorrect data for the JSON request. Switching from raw text to HTML did the trick and resolved the problem.

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

What is the best way to implement this design using CSS or JavaScript?

I would like to enhance the appearance of my school website during these challenging times of the pandemic by adding some CSS or JavaScript elements. However, I am unsure how to go about it. ...

Error: The module 'https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js' is missing the required export 'default'

I'm currently in the process of setting up and testing Google authentication for a web application that I'm developing. Unfortunately, I've encountered several issues with getting the JavaScript functions to work properly, and I am uncertain ...

A guide on crafting OR queries in Elasticsearch using Node.js

I currently have a document structured like this: Sample document, [ { "_index": "xpertdox", "_type": "disease", "_id": "Ectopic Heartbeat", "_score": 24.650267, "_source": { "category": "Condition", "name": "Ectopic ...

Installing the error package resulted in the following error: "Error: module 'nopt' not found."

After attempting to install node modules, I encountered the error message "Error: cannot find module 'nopt'." I tested various solutions, but none of them seemed to work. The image below shows the attached error message. { "name": "server", ...

How can I load data into Vuex store before the application starts?

Within the created hook of App.vue, I am initiating a dispatch call to my store. Subsequently, in a child component, I attempt to retrieve this data using a getter. However, an issue arises as the child component is loaded before the data is stored, causin ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Spring Boot Thymeleaf endpoints are not compatible with my ajax requests

Currently, I'm developing a basic crud system with spring boot and thymeleaf. However, I've hit a roadblock as I'm unable to consume my spring endpoints using simple ajax. Controller @Controller public class StudentController { @Autow ...

What steps are needed to successfully enable the callback function within the addFilter method from @wordpress/hooks while customizing the tables in WooCommerce analytics reports?

I've been diving into customizing Analytics reports tables for clients on our WooCommerce platform. I followed a guide at this link, but encountered an issue with the JavaScript file. After adding the filter at the end of the file as instructed, noth ...

Issues with displaying images in CSS when using HTML 5 canvas drawing

In attempting to draw an image on a canvas using a pre-loaded image and CSS, such as: img.style.backgroundColor="red"; ctx.drawImage(img,0,0,100,100); I have observed that the image is drawn without incorporating the CSS modifications. Are HTML canvases ...

Is it possible to use async in the onChange handler of a React event?

Can async be used to pause execution until a function completes within an onChange event? Here is an example: const onChange = async (e) => { console.log(current[e.target.name]); await setCurrent({ ...current, [e.target.name]: e.targe ...

Enabling direct access to sub-folder files within the root of npm imports

A new npm module I am creating has a specific folder structure: lib/ one-icon.jsx another-icon.jsx /* about 100 more */ package.json I would like to import these files in this manner: import OneIcon from 'icon-package/one-icon'; However ...

What is the best way to use `JSON.parse` in jQuery to accommodate older browsers?

Is there a way to internally call the function in jQuery that performs JSON.parse? I need to support IE8 and IE9, which don't have JSON.parse available. This means I can't simply use it in my code, so I'll have to rely on an external librar ...

Guide on utilizing two separate collections to store different types of data for an application's users

I am looking to create a database collection similar to {username : "jack", password : "pass"} for storing doctors' login information. I believe I can achieve this during signup by implementing the following code: var Doctor = mongoose.model("doctor" ...

Changing the color of a progress bar in Bootstrap based on a specific percentage level

var elem = document.getElementById("progress-bar"); var progress = 75; elem.style.width = 80 + '%'; if (progress > 80) { elem.style.background = "red"; } #myProgress { height: 5px; } #progress-bar { w ...

When invoking a function, a React Component utilizes the props from the first element instead of its own

Whenever I try to invoke a function of a component, it seems to be replacing the parameters and passing the props of the first array element instead of the selected one. To illustrate this issue, let's take a look at some code: Firstly, here is how ...

Retrieve the URL of the previously visited webpage using Javascript

Is there a way to retrieve the URL of the last visited page using JavaScript? I want to be able to track which product the user viewed most recently. I have attempted the following code: var x = document.referrer; document.getElementById("demo").innerHTML ...

Customize the CSS for the column containers in Material-UI's DataGrid with the

I am facing a challenge in trying to override the CSS property position on the .MuiDataGrid-columnsContainer. Upon reviewing the information available on https://material-ui.com/api/data-grid/#css, it seems that there is a rule defined for root but not spe ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...

Troubleshooting a problem with jQuery child items

Could someone help me understand why the second div is affected by the last part of the code and not the first? It's puzzling to see all the content disappear, especially when I expected the first div to be impacted as it seems like the immediate pare ...

Executing a npm script (script.js) with custom arguments - a step-by-step guide

I'm considering creating a setup similar to lodash custom builds. Basically, I want to allow users to input a command like: lodash category=collection,function This would create a custom module with the specified category. I've been looking in ...