2

Is there a way to have the same behavior as a link_to ... remote=> true with javascript?

maybe it's not necessary -

I have a div with the user's name and picture in it.

I want to have the entire div to react to a click and go to the method (users#show for example) as if it were a link_to.

The problem with link_to is that it creates a href, making the text linkable etc.

Also, I can't seem to use it to make the whole div clickable, only the text.

In an attempt to explain myself more -

If link_to corresponds to window.location in javascript

what is link_to with :remote=>true in javascript?

Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244

3 Answers3

2

This is how you do it:

$.rails.handleRemote($('<a>', { href: '/path', 'data-method': 'GET' }));

marano
  • 722
  • 6
  • 9
0

I'm not entirely familiar with Rails, but after reading the description of the method, it sounds like you're simply doing an ajax call. It's funny how much Rails abstracts this concept.

If you're using a library like jQuery, doing an ajax call on click is very simple:

$('element').click(function(e){
  $.get('url', function action(){
    // Do stuff
  });
});
THEtheChad
  • 2,372
  • 1
  • 16
  • 20
  • is $.get identical to :remote=>true with GET? – Nick Ginanto Jan 24 '13 at 06:49
  • No. I don't think he understands what remote=true does with rails. – Ultimater Jan 24 '13 at 06:54
  • It's like I said, I don't know what link_to does, which means I don't fully understand the question, but I guarantee you if I knew what you were trying to accomplish, I would have a solution. – THEtheChad Jan 24 '13 at 07:22
  • :remote=>true -- This will allow the unobtrusive JavaScript driver to make an Ajax request to the URL in question instead of following the link. The drivers each provide mechanisms for listening for the completion of the Ajax request and performing JavaScript operations once they’re complete. Based on that description, it does a request to a url and then performs an action. Since the click event on a div does nothing, you won't be redirected. If you're using this on a link, you'd add e.preventDefault(). – THEtheChad Jan 24 '13 at 07:24
  • He's using the jquery-ujs library which interacts with Rails: https://github.com/rails/jquery-ujs/blob/master/src/rails.js notice the `a[data-remote]` selector. – Ultimater Jan 24 '13 at 07:34
  • Gotcha! Thanks for the clarification. I have no desire to learn the inner workings of that library. Good luck, sir! I hope you find your answer. – THEtheChad Jan 25 '13 at 07:13
0

To have a DIV work with remote=>true, after inspecting jquery-ujs carefully, it would seem you could wrap the DIV which you want clickable around a FORM like so:

<form action="/users" method="POST" data-remote="true">
   <div onclick="$(this.parentNode).trigger('submit.rails');">Remote Request</div>
    <input type="submit" style="display:none" />
</form>
Ultimater
  • 4,647
  • 2
  • 29
  • 43