Jump to content

The ultimate community for Ruby on Rails developers.


Photo

absolute path for preventDefault();


  • Please log in to reply
3 replies to this topic

#1 kristers_Z

kristers_Z

    Passenger

  • Members
  • 5 posts

Posted 02 November 2013 - 04:46 PM

I'm facing very weird problem and I really need explanation about how things work here.

 

I have a lot of delete links for different items. I want it to be in ajax-way, like so: when user click on delete link, JS prevents link's default behaviour (to redirect page) and then JS makes AJAX request. Such JS would be something like this:

$('a').click(function(e){
    e.preventDefault();
    alert('default prevented');
    // ..and then make ajax request
})

Those delete links are generated by link_to helper like this:

<%= link_to('Destroy', item, method: :delete ) %>

And the actual HTML is:

<a data-method="delete" href="/items/144" rel="nofollow">Delete item</a>

However, this DOES NOT work - preventDefault() does not prevent default. I mean - on click alert 'default prevented' fires, but when I click 'ok', page gets redirected to link's href. Which is not what I want.

 

After being stuck here for a few hours I found the problem, but didnt understand why is it like so. 

The problem is - link_to href is relative. If I make it absolute, like this:

<a data-method="delete" href="localhost:3000/subjects/144" rel="nofollow">Delete subject</a>

..then JS suddenly works, event gets prevented, page doesnt redirect and I can make my Ajax call.

Why do I need absolute path to make JS work?



#2 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 03 November 2013 - 12:08 AM

If you're attaching click events to your <a> tags, and you're calling the delete program via ajax, why not just make href hardcoded to '#' ?

 

i.e.  <a href="#" id="delete-this-task">Delete</a> 



#3 kristers_Z

kristers_Z

    Passenger

  • Members
  • 5 posts

Posted 03 November 2013 - 09:58 AM

If you're attaching click events to your <a> tags, and you're calling the delete program via ajax, why not just make href hardcoded to '#' ?

 

i.e.  <a href="#" id="delete-this-task">Delete</a> 

 

Ajax picks up 'url' parameter from <a> tag's href attribute.



#4 Ohm

Ohm

    Guard

  • Members
  • 179 posts
  • LocationCopenhagen

Posted 03 November 2013 - 10:16 AM

Couldn't you just add 

remote: true

to your 

<%= link_to('Destroy', item, method: :delete ) %>

like so

<%= link_to('Destroy', item, method: :delete, remote: true) %>

?

 

Else, you should be able to get absolute paths with the url_for helper like so

<%= link_to('Destroy', item_url(item), method: :delete) %>

Blog: http://ohm.sh | Twitter: madsohm





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users