Hima Chhag Hima Chhag - 2 years ago 91
HTML Question

Anchor tag follows url even after doing element.preventDefault() in jQuery Script

I am trying to delete an element with jQuery. EVerything works fine but for some weird reasons, even after doing element.preventDefault() in script, anchor tag follows href after deleting goal and gives ActiveRecord::RecordNotFound error. I understand that record has been deleted so it is giving ActiveRecord::RecordNotFound error after trying to open up that page. But I don't understand what else I can do to stop it from vising any page.

<% if current_user == @habit.user %>
<% habit_id = @habit.id %>
<% goal_id = goal.id %>
<a href="/habits/<%= habit_id %>/goals/<%= goal_id %>" data-confirm="Destroy <%= goal.name %>?" data-method="delete" class="jquery-postback" rel="nofollow">Delete Goal</a>
<% end %>

$(function() {
$(".jquery-postback").on('click', function(element) {

var $this = $(this);

type: $this.data('method'),
url: $this.attr('href')
}).success(function (data) {

I tried to play a lot with script and anchor tag but couldn't find any solution. Any suggestion to solve this error?

ps: this functionality allows user to delete goal from the habit show page.

Answer Source

I finally found a solution. If anyone else is having the same problem, if you rewrite anchor tag without data-method="delete" and rel="nofollow" it would work.

Something like this....

<a href="/habits/<%= habit_id %>/goals/<%= goal_id %>" data-confirm="Destroy <%= goal.name %>?" class="jquery-postback" >Delete Goal</a>

The reason behind is, Rails comes with some helpers that create event handlers for all the "delete" actions generated by Rails. This is the JQuery code that Rails uses:


So, the event handler will be the only one executed if anchor tag is without data-remote and data-method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download