2

I was trying to replace my div in DOM using RJS. Here is the code i tried, The controller has this method:

def change
  render :update do |page|
    page.replace(:test_id, :partial => "input",:locals =>{ :type => 'text', :name => 'user[user][contactinfo][city]', :val => "", :size => '244', :placeholder_text => 'Yes it is working...'})
  end
end

The view contains:

<div id = "test_id"></div>
<%= link_to "AJAX", "/poc/change", :remote => true %>

Now I want to replace the div id="test_id" with the partial mentioned.

The output i get is:

try {
Element.replace("test_id", "<input type=\"text\" id=\"user[user][contactinfo][city]\" name=\"user[user][contactinfo][city]\" value=\"\" placeholder=\"Yes it is working...\" style=\"width:244px; height:33px; border:0; color:#646464; background:url(/images/form_textfield_244.png) 0 5px no-repeat; padding:12px 5px 0 5px; margin:0 0 10px 0;\" />\n");
} catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.replace(\"test_id\", \"<input type=\\\"text\\\" id=\\\"user[user][contactinfo][city]\\\" name=\\\"user[user][contactinfo][city]\\\" value=\\\"\\\" placeholder=\\\"Yes it is working...\\\" style=\\\"width:244px; height:33px; border:0; color:#646464; background:url(/images/form_textfield_244.png) 0 5px no-repeat; padding:12px 5px 0 5px; margin:0 0 10px 0;\\\" />\\n\");'); throw e }

This is seen in browser. Can anybody explain where I am going wrong? The expected output is the div should get replaced with whatever given for replacement.

pjmorse
  • 9,204
  • 9
  • 54
  • 124
Aashish P
  • 1,894
  • 5
  • 22
  • 36

1 Answers1

6

I advise you do not use RJS anymore. The better is generate a JS view with you want your javascript do.

By example if you use jQuery you can add a file :

changes.js.erb

Inside you add you Javascript :

$('#test_id').html("<%= escape_javascript(render :partial => "input",:locals =>{ :type => 'text', :name => 'user[user][contactinfo][city]', :val => "", :size => '244', :placeholder_text => 'Yes it is working...'}) %>")

Now if you call the /proc/change.js you can see the JS generated like if you do some JS in you page.

TKH
  • 828
  • 6
  • 11
shingara
  • 46,608
  • 11
  • 99
  • 105
  • What is the problem with RJS ? – Aashish P Mar 22 '11 at 13:59
  • @AashishP RJS is deprecated and buggy, as it generates JS for you. with unobtrusive JS patterns, you write your own JS therefore you have control over your event bindings. RJS also forces you to send JS over the wire, which is a bad idea because it relies on the browser to properly execute the JS, which it never does. It's more reliable to send JSON or HTML data over the wire, then do any extra processing on the `ajax:success` callback. you should *never* send HTML and accompanying inline JS in the same response, unless you like solving `$ is not defined` errors... – tubbo May 21 '12 at 19:19
  • is there anyway to also replace the id of the div?? – wachichornia Aug 03 '12 at 13:48