0

I am experimenting with Rails and the AJAX helper - remote: true. I have a view with a link:

<%= link_to 'My Profile', edit_user_path(current_user), class: 'user-profile', remote: true %>

This fires an AJAX request to a controller:

  def edit
    @user = User.find(params[:id])
    respond_to do |format|
      format.html
      format.js { render plain: "Test" }
    end
  end

Which returns "Test" to my js ajax listener:

$(document).ready(function() {  

  $('.user-profile').on('ajax:success', function(response) {
    console.log(response)
    let data = response.detail[0]
    $('.profile-content').append(data)
  });

  $('.user-profile').on('ajax:error', function(event) { console.log(response) })

})

Everything works as expected. "Test" is appended ( I have also appended views and JSON objects). However, whenever I get a response back, I get a JS error in my console: enter image description here

If I render an HTML view then I get:

enter image description here

What could be causing this? Its driving me mad because everything works as expected but I get an error.

Darkisa
  • 1,899
  • 3
  • 20
  • 40
  • 1
    Use the json format instead, like `format.json { render json: { data: 'Test' } }`, note the json sent from the controller is a hash which you'll have to parse. – Sebastián Palma Jan 14 '18 at 21:14
  • That worked. Thanks. Any idea why just rendering plain text would cause an issue? – Darkisa Jan 14 '18 at 21:25
  • I'm not sure, but did you try by parsing the received data when sending a plain text? – Sebastián Palma Jan 14 '18 at 21:26
  • I did not. I will give it a try now, but I think you're right. I'm guessing JS processor doesn't know the response format without me explicitly defining it. Thanks for your help! – Darkisa Jan 14 '18 at 21:29
  • You're welcome, if you get a conclusion, you can answer and accept your own question. – Sebastián Palma Jan 14 '18 at 21:31
  • Not related to the question itself, but you shouldn't send `current_user` as a parameter to the edit method. instead just use `@user = User.find(current_user.id)` in the edit method itself. otherwise people could edit the html code and send whichever user id they want. – Ziv Galili Jan 15 '18 at 02:26
  • That’s what I was wondering when I set it up, but if a user has to login to use the edit form, then wouldn’t that allow me to use current_user instead of User.find ? To reduce database hits, that why I used current_user since it’s cached and it’s the object I need to edit. – Darkisa Jan 15 '18 at 05:16
  • I am reading https://stackoverflow.com/questions/7052650/link-to-and-remote-true-jquery-how-help#8673600 – Fabrizio Bertoglio Jan 15 '18 at 07:10
  • @FabrizioBertoglio that link is helpful. thank you. – Darkisa Jan 15 '18 at 17:42

0 Answers0