What would be the best way to send an alert message to the user if it requires them to login, but at the same time avoid an ajax call? I might have code like <a href="#" id="vote">
which would trigger an ajax function based on the click. I was thinking I would check on the server side if a user is logged in and replace it with:
<a href="#" class="not-logged-in">
. If that is clicked then it will alert them that they need to log in. The problem is that I might have some css styles for the #vote. If instead I make it <a href="#" id="vote" class="not-logged-in">
it would trigger both the ajax call and alert, so I'd have to wrap the ajax call around with a check to see that the not-loggin-in class does not exist, but it seems a bit tedious to do that for all my click functions that have ajax calls. Or either I would call the parent id and set the style like #parentId a{}? Or is there any better methods? I'm not sure what people usually do, so looking for some opinions. Thanks!
views:
153answers:
3How about this:
The HTML:
<body class="not-logged-in"> -- or -- <body class="logged-in">
<a href="/vote/13" class="vote">Vote!</a>
The jQuery:
$('body.logged-in .vote').click(function(){
$(this).append($.get($(this).attr('href'));
return false;
});
If your click handler for the a#vote
element is tied to the vote
id, you'll have to either change the id for the logged out users or add a conditional to the click handler.
You mentioned that you don't want to check for the not-logged-in
class before proceeding with the AJAX call, so I'm assuming this means you'd rather leave the click handler alone and come up with some other way to have the link look like the vote link but not act like the vote link.
You could make an alternate id and give it the same styling, like so:
HTML:
<a href="#" id="fakeVote">
CSS:
#vote, #fakeVote { /* CSS here */ }
The nice thing about this is that you can just add a new click handler for the a#fakeVote
element to alert the logged out users.
If you want to reduce the DOM lookup time with each click just attach the "loggedIn" class to body element and do the check right after page load.
var loggedIn = $('body').hasClass('loggedIn');
Now, you don't have to make a check on the link itself but rather on that variable.
Alternatively, write a wrapper for your ajax calls.
$.fn.ajaxLoggedIn = function() {
if (loggedIn) {
$.ajax.apply(this, arguments);
}
else {
alert('You are not logged in');
}
}