Javascript auto update page? - javascript

Can anybody give me a direction, I want to know how to do auto updating pages like facebook have for new status updates, new likes etc. Ie., if you have a status open in a window and a user click "like", the +1 like automatically appears.
Thanks in advance.

These are done using a PUSH model (subscribe / publish).
The client side first subscribes by issuing an AJAX request. This AJAX request stays alive indefinitely. When the server receives a new like / comment, it publishes this update to the client side thereby ending the AJAX request. The client receives this update and isntantly issues another AJAX request.
It is broadly categorized as Comet.
Once before, I had implemented a Comet web chat application and wrote a somewhat technical write up of what went into it. You can read it here, if interested.
Comet Web Chat Application
Edit:
A heartbeat mechanism (PULL model) is definitely easier to implement, but a PUSH model is far more efficient.

You'll need to use ajax, which is a way to communicate with the database without reloading the web page : you could for example use the
$ajax
function of jQuery framework : here's the doc

im not posting code, but here's a quick overview of what you might wanna do:
have the "like" image
create a script that binds a click handler to the image.
once clicked, the script sends an AJAX request to the server to increment the like
if that request succeeds, return data to the script indicating that it was a success. you might also want to return the number of likes and so on.
once the script knows the success, have it change your "like" image.
as for counting likes, well, its up to you. for a very broad question, this is a broad answer that will point you to the right path.

Related

Node.js + Express: How to update page when something has been inserted into database?

I have messaging all set up, but when someone sends a message, I want the recipient to see the message without having to refresh the page.
It would also be cool that when a user receives a message, there is a notification/badge that appears to indicate a new message.
I'm a newbie only just delving into web development, so is this the scenario where I would use AJAX? I've been reading about it, and that seems to be the case. Is there a better way to do something like this with Node.js + Express?
I just need a push in the right direction. Thanks!
THere is a very good nodejs module for long pooling - http://socket.io/
So, you can send message from server when record is updated
Having the recipient see a message without refreshing a page can be achieved by AJAX. Your situation where you want the user to receive a notification message is a common one. There are several ways of achieving that. You can do short-polling or long-polling, both of which can be achieved by AJAX Scaling a chat app - short polling vs. long polling (AJAX, PHP). But if you're using Node, why not look into websockets. Node and sockets literally go hand-in-hand. Good luck!

Twitter like new tweet count notification in ASP.Net

I have very limited knowledge in jQuery. I need to develop a page which should show the count of new message posted. In twitter and stackoverflow websites, I have seen a div which shows the count of new tweet/questions posted and while clicking on it, the newer ones are shown on the top. Below added are the sample images:
Please suggest whether it can be attained using jQuery or Ajax.
Thanks
Those examples look like push rather than pull behaviors. By this I mean that the server is saying to the page 'hey there is a new tweet in this tag' rather than the page asking 'is there any new tweet? No not yet? OK, I'll ask again in 5sec'.
Since you are on ASP.NET, you can easily push notifications from server to client by using the good SignalR library.
You still have to detect on the server that there are new 'things' and send a message (with signalR) to the matching clients. And also handle the message on the client and show a piece of UI.
As you are using ASP.NET, you can use an UpdatePanel to help handle making the call and updating your content. Note that the UpdatePanel uses AJAX, and can be set to automatically update on a specified time interval.
What I would do, if I were you, is use the UpdatePanel to call a method that makes a request to the Twitter API and grabs all of the new tweets that you have not already grabbed. Then count the number of tweets returned and, if that number is greater than zero, I would display the "X tweets with new activity", or whatever counter message you are looking to show.
If you are not strong with jQuery, this may be the best solution for you, as you could get away with using the UpdatePanel and a Repeater to render out your tweets, and update the ones displayed when clicking a button/link/etc, with or without postback (whichever is your preference for this implementation).
Important Side-Note
Note that Twitter API v1.1 requires you to use oAuth Tokens, which should not be included in AJAX calls. You should only be using server-side code to make requests to the Twitter API, and, thus, this solution is likely to be the best for you, as you can write your request code in the code-behind (thus keeping your Twitter keys and tokens safe), and call it using the UpdatePanel.
Update
I am not usually one to promote my own libraries on Stack, but if you need help with making the request to Twitter's API using oAuth, take a look at my C# library for Twitter requests. The documentation includes instructions for setting up oAuth access on Twitter and is very verbose in helping you make calls with the library. It also includes MSDN-style documentation for the library, itself, an example request, and full IntelliSense for all classes, methods, and properties. If nothing else, it should help you set up your requests. If you have any trouble with it, let me know and I can help you out.
You need to retrieve the new messages using a $.ajax call which you repeat every few minutes or so using setTimeout. But for that ajax call to work you have to have some sort of API endpoint you can retrieve the data from.
This is not just something you can build by dropping in a jQuery plugin somewhere and be done with it. You need to have knowledge about Javascript, jQuery and your specific API before you can do anything. Try checking out the jQuery basic tutoorial.
You can create a WCF service to get latest messages which you can call using setTimeout to update your message div in real time using Ajax or you can use SignalR to add real time functionality.

How to "Secure" AJAX calls?

I'm sure this question has been asked before, but I can't find a thread that explains it in a way that makes sense to me.
I'm creating a bookmarklet/browser plugin written in Javascript. This script makes calls to an api, effectively sending a users activity information from one site to another. (think, making a tweet when a user posts a facebook status)
This site loads javascript right into the site. The API I'm using requires an MD5 hash to be generated using an API secret code. This is no problem, I'm making an ajax call to a PHP script I'm hosting elsewhere, that returns the correct string.
Problem is I don't want the user to be able to make a call to this same script to generate their own strings, with the secret embedded to abuse the API. Is their a way I can only allow calls to this API when I want to make them?
Or maybe I'm approaching this from the wrong direction.
You cannot dictate how a client executes your javascript. There is no way to create a "secure" request, or insure that it wasn't modified by an attacker. This is the nature of the client/server system. The page its self can be modified using GreaseMonkey and any request can be modified or replayed using TamperData.
1) you should open a token on your DB like GUID.
this guid will represent some info and can only be executed once ( put a db field in table called "isAlreadyuse" -type bit).
now ,
when the ajax will call itself - you send this guid to the server.
the server will see if the guid exists
and emits its logic and update thefield to "1".

How to update asynchron pages upon event from other client?

I'm currently fooling around with AJAX. Right now, I created a Markdown previewer that updates on change of a textarea. (I guess you know that from somewhere... ;-) ).
Now, I'm trying to figure out, how to update a page upon an event is fired from another client. So to say an asynchron message board. A user writes something, an event is called, the post is written.
But on the other clients' pages, the new post is of course not yet available until they reload and get the updated list of posts from the database.
Now, how can you get this to work asynchronously? So in that moment when one client does something, the other clients all get to know that he did something?
I don't think this can be done completely in AJAX, but I also have no idea whatsoever how to implement this on server-side, as it would require a page reload to inform the other clients of the event.
I'm thinking of creating a file or database entry that hashes the current state of data. Whenever a client loads the page, he saves this hash. Then, a timer (does this exist in JavaScript?) checks for the hash every few seconds.
As soon as anyone changes the databse, the hash is recalculated. If the script sees that the hash was changed and is different to the one saved, it reloads the contents form the database and saves the new hash.
Is that even going to work?
Polling that is light as possible is really the best solution here. Even if you did use a socket or something... That's still basically a live connection waiting around that will likely have to poll itself (albeit in a more effecient way).
20 queries in 10 minutes that have responses like {"updates":false} shouldn't even be putting a dent in your application. I mean imagine someone browsing your site requesting 20 pages and the related images/scripts/etc (even if some caching is involved), there could easily be hundreds of requests requiring all sorts of wasted database queries to information to be displayed on the page they don't actually care about.
You could use polling. For example each client might be sending continuous AJAX requests to the server say each 30 seconds to see if new posts are available and if yes, show them:
setInterval(function() {
// TODO: Send an AJAX request here to the server and fetch new posts.
// if new posts are available update the DOM
}, 30 * 1000);
On the other hand when someone decides to write a new post you send an AJAX (or not AJAX) request to the server to store this post in the database.
Another less commonly used approach is the concept of Comet and the HTML 5 WebSockets implementation which allow the clients to be notified by the server of changes using push.

how to update a Django page without a page reload?

My Django app displays data from a database. This data changes without user intervention, i.e. behind the scenes. Whenever it changes, I would like the webpage to update the changed sections without a full page reload.
Obviously AJAX springs to mind. When the page is loaded initially (or manually, fully re-loaded later on), the rendered template loads a JavaScript that runs window.onload = update("all"), update(...) in turn triggers a number of XMLHTTPRequests which again return data that gets transformed into HTML pieces for the corresponding sections. All works fine. At the initial page load.
Now I find myself in a Python function that saves a new object to the database.
How do I tell the browser to run update(...) ?
Do I need to somehow manually issue a request to a url that is mapped to a view which in turn renders a template that contains the JavaScript code to run update(...) ??? Oh my!
I feel like I'm not following the usual approaches.
Maybe I'm just standing to close in front of the problem.
Can anyone help me ?
2021 update: Use channels: https://channels.readthedocs.io/en/latest/
You have two choices
Have the browser poll using setTimeout()
Look into Comet -- this is a technique for pushing data from the server to the browser.
Here's an article on Comet in Django
two approaches:
just update the database and wait until the next AJAX query. That means it should do the query periodically, you'll have to balance between immediacy and server load. It helps a little if you can do a cheap query to just verify if there has been an update. Maybe make that check rely only on memcached instead of going to the DB
use comet. In short: the client does an AJAX query asking for the update. the server sees there's no update, so it doesn't answer. Instead, the connection is kept open for a long time. Eventually either the update comes and the server finally answers, or the client times out and kill the connection. In that case, the client should immediately reissue the query to keep waiting for the update.
You can also use The Websocket API https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

Categories