I am using Ruby on Rails 3.0.7 and jQuery 1.6.1 and I am binding an AJAX click event to a link_to
HTML output as in the following example:
link_to 'Link name', '#', :id => 'link_css_id'
As you can see I set the URL to '#'. Doing that when I click on the link the current view will be moved at the top of the page, as well. Since I don't like this behaviour, I set nothing (that is, nil
or ''
) for the URL parameter, but on clicking on the link I get an alert message "error" that immediately after disappear. Then in the Firebug Console I get:
uncaught exception: [Exception... "prompt aborted by user" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: resource://gre/components/nsPrompter.js :: openTabPrompt :: line 468" data: no]
How can I solve this issue and avoid the behavior of going at the top of the page on clicking the link?
The AJAX request is:
$jQ('#link_css_id').bind('click', function() {
$jQ.ajax({
type: "POST",
url: "<%= user_url(@current_user)%>/test_method",
data: "test_data=test",
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
$jQ('#css_id').html('error')
},
success: function(data, textStatus, jqXHR) {
$jQ('#css_id').html('success')
}
});
});
The url "#" means an internal anchor is being set. With no name attached to it, it simply focuses on the whole page, and scrolls back up to the top.
As for using the link_to
method, the url
attribute is required and cannot be omitted.
With jquery, you can use preventDefault
. This will prevent the default action from the event (e.g.., clicking on a link will open the href
url). This is quite useful. You might want to link to an existing page for users that do not have javascript enabled (and where the ajax call won't work), while it is being ignored by those who do have javascript.
preventDefault documentation by jQuery.
you can set javascript:void(0)
instead of #
it help me.
Keep the #
, and use preventDefault
to stop the default click event from moving the window.
User contributions licensed under CC BY-SA 3.0