Nick Ginanto
Nick Ginanto

Reputation: 32120

doing a remote => true call with javascript

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?

Upvotes: 2

Views: 1674

Answers (3)

marano
marano

Reputation: 742

This is how you do it:

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

Upvotes: 2

Ultimater
Ultimater

Reputation: 4738

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>

Upvotes: 0

THEtheChad
THEtheChad

Reputation: 2432

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
  });
});

Upvotes: 0

Related Questions