0

I have a Rails app where I created an AJAX / JSON controller to do some dynamic HTML updates in the view. I followed this guide: https://www.rubyguides.com/2019/03/rails-ajax/

I make a call like this: ../related.json?vendor_id=1&budget_id=1 and it returns the raw HTML partial I want to update (just a bunch or table rows).

My call looks like this:

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

If I manually view the JSON request in the browser the HTML output is as expected. However when I try to replace the HTML or even view the data in a test alert I get back [object HTMLDocument]. The guide I followed used data.html to feed the innerHTML but that doesn't work for me. Not sure if that's a UJS / JQuery issue.

How do I set that DOM element with the raw text from the JSON call?

2 Answers 2

1

You can convert a raw text to html with JSON.stringify function:

document.getElementById("related").innerHTML = JSON.stringify(data)
Sign up to request clarification or add additional context in comments.

2 Comments

That returns {"location":null}. I double checked my JSON source - it is returning plain text (HTML) - on headers etc. Just the <tr> rows.
Upvoted your answer because it made me think more about my controller side which was the ultimate answer. 👍 . Thanks.
0

I did some digging and tried this in my controller:

format.json { render  partial: 'related' } 

vs

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

This did the trick - I figured that I was feeding the JSON request the wrong data - looks like once I feed it raw text vs html it works fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.