Reputation: 393
I am trying to submit an ajax function via a link click, I am using onclick like so:
<a href="<?php echo SITE_URL; ?>watchlist/remove/<?php echo System::escape($this->item->item_id); ?>" onclick="manage_watchlist(); return false;" id="watchlist">
Remove From Watchlist
</a>
and my function:
var manage_watchlist = function(e)
{
alert("ff");
e.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: 'post',
dataType: 'json',
success: function(data)
{
if(data.success)
{
if($(this).hasClass("remove"))
{
$(this).text("Add to Watchlist");
$(this).removeClass("remove").addClass("add");
$(this).attr('href', '<?php echo SITE_URL; ?>watchlist/add/<?php echo System::escape($this->item->item_id); ?>');
}
else
{
$(this).text("Remove from Watchlist");
$(this).removeClass("add").addClass("remove");
$(this).attr('href', '<?php echo SITE_URL; ?>watchlist/remove/<?php echo System::escape($this->item->item_id); ?>');
}
$('#watch_success_message').html(data.success + alert_close).show();
}
else
{
$('#watch_error_message').html(data.error + alert_close).show();
}
<!-- hide loading icon -->
$('.ajloading').hide();
},
error: function()
{
<!-- hide loading icon -->
$('.ajloading').hide();
}
});
return false;
}
I have put an alert in the function which works so my function is working, but it is still visiting the link for some reason?
Upvotes: 1
Views: 80
Reputation: 262
When you put code into the string for onclick it does not act as you may think it does. It behaves similar to this:
function(event) {
manage_watchlist();
}
which is why you must pass the event object to your function in the html onclick.
onclick="manage_watchlist(event);"
will look like
function(event) {
manage_watchlist(event);
}
Upvotes: 0
Reputation: 9460
Do something like this:
<a href="<?php echo SITE_URL; ?>watchlist/remove/<?php
echo System::escape($this->item->item_id); ?>" id="watchlist">
Remove From Watchlist
</a>
//JS
$(document).ready(function(){
$('#watchlist').click(function(e){
var $this = $(this); //**this** is the anchor
e.preventDefault(); //e is click event.
$.ajax({//use $this when you mean the anchor
//**this** here is $.ajax
//...
//your code here
});//$.ajax
});//$('#watchlist').click
});//$(document).ready
Upvotes: 0
Reputation: 263
For an inline event e.preventDefault();
"prevents" return false.
Use only return false;
.
Upvotes: 0
Reputation: 207501
You need to pass in event with the inline event handler.
onclick="manage_watchlist(event);"
or better yet, dump the inline event and use jQuery to attach the event.
Upvotes: 3