catch hyper link clicking with javascript(or jquery)? - javascript

When a user clicks a link in his inbox, I want to mark the message related to the link as seen.
SO has this feature as well,
If someone replies to my post, SO shows something happend to my post.
After I click the inbox message and visit the post, SO no longer shows notification mark.
I guess it's too expensive to test if visiting user of a question has an inbox message every time a user visits any question page.
I wonder if it's possible to catch clicking-link in the inbox page, so that I can send ajax request under the hood to mark the message as seen
Hope my questions are clear.

Add a custom data attribute to each message you click. I'm not sure how your displaying messages, but for this example we'll use a span:
<span class="message">Some Message</span>
And the JS:
$(".message").click(function() {
$(this).data("visited", true);
});
Then you can check spans to see if they've been visited. If you still want to do the AJAX call, you can simply add an AJAX event inside the click handler as well.

I'm assuming you have some sort of 'status' field on your messages table to differentiate between 'Read' and 'Unread'.
If you are asking how to efficiently store the number of unread messages in an inbox without running a query on every page load, this can easily be accomplished by setting a $_SESSION variable:
$_SESSION['unread_messages'] = 2;
After this variable is set, you can periodically check (every 5 minutes or so) to keep this up to date within a reasonable window. When a message is clicked and read, you will subtract 1 from this value or re-query the number of unread messages.
If you are asking about how to update the database and UI, there are 2 main ways you would go about doing this. It will depend on what currently happens in your script when a user clicks on a message. Do you make an AJAX request to load the message, or does the link take the user to a different page?
If you make an AJAX request when a message is clicked, simply have the script that is called in the AJAX request also mark the message as read (in the database), and use JavaScript to make any UI updates to the current page (such as removing bold text on the message that was clicked).
If clicking on a message redirects to a different page where the entire message is displayed, you can mark the message as read in the database when that page loads.

Related

Keep data in divs when comming back from other page

Firstly, I didn't know how to give a short description of the problem in the title, let me explain it here.
I'm creating social site, with all common features like/comments etc. Imagine Twitter/Instagram. I do have main/home page where all posts are displayed. Every post has a like button, so when it is clicked it triggers a AJAX function to send request to Django server to update the database with new like. This JS function also changes the style of the button, so user can know that he liked it. So far so good. Now when he decides that he want to comment this post, he clicks it and is redirected to the new page - the detail page. Here when the page is loading with data from server his like he gave earlier is visible(the div is red). All right, he commented, but know when pressing back button, in order to go to the home page, his like under the post is not more visible without reloading the page. I will demonstrate it using images.
Now I'm using JS function to reload whole page, to get from Django server all new data, but I don't think it is good idea.
<script>
if (!!window.performance && window.performance.navigation.type === 2) {
// value 2 means "The page was accessed by navigating into the history"
console.log('Reloading');
window.location.reload(); // reload whole page
}
</script>
Is there a better way of doing this?

How can I retain like count from a button after a refresh? [duplicate]

I looked on SO, here, a few other places & ... cluelessness set's in.
What is the structure of the Facebook " Like " Button found all over websites ?
Is it a Social Bookmarking, Browser Button kind ?
Is there a step by step process (without using FB Api) to make my own kind of button.
How to design & implement a Like Button ?
I want my own button with similar functionality as FB but NOT related or developed on their platform! I am trying to input this in iWeb'09 as a html widget.
I've done this successfully. Here's how i did it:
You have a table in a database called "likes" with fields username,postid (and date, id if you want too)
Each post/blog/article should have its own id.
When someone likes a post/blog/article, you take the id of the post/blog/article and the username who liked it and check the likes database to see if it already exists. If it already exists, you remove the like. If it does not exist you add a like.
For example with AJAX, this is how i did it specifically:
I have a blog post with id 6.
Jonathan likes this post.
These 2 variables are sent via a post form and wait for a response, likes logic checks database to see if this record already exists in likes table (username,postid) values ('Jonathan', 6) if the response is 1 (or true), then i update the div number for the likes button from whatever value was there originally and add 1. If the response is 0 (or false) then i take the original value in the likes counter and remove 1.
To answer your question consider what happens with buttons and then go into like buttons.
Pressing a button triggers an event on client which may or may not update a server somewhere to notify that a button has been pressed for such and such intention. You can send a lot of extra info with this event like when and where who and why etc
Like buttons usually have extra info on who liked it and what they like. In order to get that you might ask people to sign in or provide some kind of input to identify them.
Take a real world example of a like button you can implement in say javascript using any server side technology
Whoever install your script will be able to see the button. You may form it with any css or your javascript can simply load an iFrame from your server or append elements to DOM to show this button
When clicked it calls your server with person's info or at least the page url where it was called. For example google analytics uses a unique ID associated with domain url to track visitors.
when you recieve this call you can update your database/storage or anything with the tick mark that button on abc site has been pressed so lets update their likes or dislikes.
If you want your javascript can also increment the number on the same page either before or after updating your server.
When someone else visit that site the script again loads and send a request to your server so you can update the count on page but this time user does not click on like/dislike button so you dont update the record.
You may then show it as a pie chart to user on total visits to their site or page with division in people who liked it and people who did not report back (did not press the button)
If you are still wondering how you can create a button . Use CSS button generator to get one
You must first have a database where you can store various values.
Now, Whenever the user clicks the button, the value of the button stored in the database must be incremented. For this, you will need a backend language which connects you to SQL database.
So whenever the button has clicked the value of the likes in the database changes.

JavaScript popup message on database changes

I am wondering how to make a JavaScript popup message (display for 5 seconds) when a database input for specific users have changed? Kind of like the Xbox live achievement message that comes up each time you do a specific task, but i want mine to check if the level for a specific user changes and then have a popup message saying "Congratulations on reaching level x". I'm going to have a popup message for other things than just level as well so it would need to be easy to design.
I couldn't find anything online so if any of you have any suggestions, please leave me some links.
either use a timer and ask via ajax in an interval for new popups
or use websockets/websocketserver to push that info to the client

how to detect a web browser closing and log it

I want to detect and close a browser window. But before closing the browser page I need to update a SQL entry in an InUse table. There are a couple of unique situations added to this. When the EditPage.aspx opens for a (recordID record in a MstrTbl) I place an entry in the InUse table. I am tracking recno (autogenerated), userid, sessionid, recordID (MstrTbl), status, rectype, rwindicator, createdatetime, updatedatetime. I am using Session("gUserID") [all Session("variables")] when updating InUse table. The variables are fairly straight forward. But, there can be multiple users opening the same recordID, however, only 1st user in can edit. (Thus, rwindicator, Read/Write Indicator). In days of yore, you could control a vb6 app opening only once, but now in web world, a user can open multiple browsers (and records), and in this case need to be able to do so.
Okay, so if there is an InUse entry for this user, and this recordID, redirect the 2nd attempt to an error page (You can only open this record once) error, and back to the Default page for you.
Now a user is finished with a record, and can click Home (Site.Master Menu Item) or can simply click "X" in browser. I DO NOT want a "verify close" message (extra click), but where the InUse table had an [A]ctive status now needs updating time stamp and e[X]pired status. The solution can be java or jquery. I have tried several renditions of many attempts at "catching" the close with window. Using a hidden "btnCloseWindow" in a onbeforeunload functions seems to almost work a larger percent of the time, especially if I set an "alert" msg (which I do not want to do).
Code in the Window.close seems to never be able to update the InUse record. I've also tried timeout intervals. I have tried a dozen variations of different "solutions" (from other programmers attempts) but none seem reliable, if I get 2 or 3 users opening 3 or 4 of the same records, then closing them one at a time. I can create the InUse record. That's easy enough. But when a user closes a recordID, it will not update date/time stamp and status from [A]ctive to e[X]pire. I do not want to insert and delete records. This is an audit trail. But if the same userID opens the same recordID and it still shows [A]ctive, it will not allow the user to (in error) open it again.
The code in the EditPage.aspx.vb runs a Public Shared Sub (RecData.LockRec) in code behind, but then needs to run (RecData.CloseRec) when the "X" or "Home" Menu item is clicked.
In advance, any help is appreciated.
You can use window.onclose event but note you have a very small amount of time so your backend has to accept the posted event quickly. The browser will only wait for a short amount of time. So if you are doing anything complicated, accept the POST/GET from the client and then close the connection and then process the POST/GET.

Only allow authorized AJAX requests

Simplified: In my JS/PHP app I have a button. When a user clicks on the button he gets 1 point which is saved via jQuery AJAX/PHP in a database.
Of course the user now can call the script that makes the AJAX request without clicking the button. Is there any best-practice to avoid that?
I am using AJAx because I don't want the page to reload.
Update:
There are many other options how a user can earn points. Idealy I would have a JS function add_points(points) that adds the points for the user. But I know that anyone can write a script to call this function automaticly. I guess the only way is to generate a hash vor every possible point-earn action and submit this hash with the AJAX request.
One thing you could do is to generate a hash and check if that hash is new or no used in the last day for example.. making sure that the user has to get a new hash in order to press the button.
If the user is allowed to click as many times as she wants, there's no real way to prevent doing it automatically. If she's only supposed to click once (like upvoting on stackoverflow), the code your server uses to update the value should automatically confirm that she hasn't clicked it before i.e. check the database.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here */
die($content);
}
You need an audit trail to properly solve this problem
Set the status "user clicked the button" rather than "user gets 1 point", and calculate the user's score as the sum of all actions that assign points. That is the basic approach used by Stack Overflow.
That way, you have an accounting record of how user's got their points, and you can implement business rules like "only allow setting status user clicked the button once"
The way you currently do it, there is no audit trail and indeed you have no way of knowing why users have the score they do.

Categories