Best way to notify browser on database updates? - javascript

I have been using django for almost 6 months now and it works fine for almost all kind of websites I do.
However , recently I stumbled upon an issue when I was doing a website, where a user gets notified about any blog post the other user updates.
My approach was this :
From my template I keep doing an ajax call like this :
$(document).ready(function() {
setInterval(function(){get_updates();}, 10000);
function get_updates(){
$.ajax({
type: "GET",
datatype: 'json',
url: "{% url 'models.views.update_notification' %}",
success: function(data) {
if(data.updated){
$.("content").load('notifications.html');
}
}
})
})
});
}
class UpdateNotificationView(View):
def get(self, request):
user = FriendUser.objects.get(name='friend')
msg = {"updated" : user.is_updated()}
return HttpResponse(simplejson.dumps(msg))
Assuming that notifications.html is just a partial included in every page:
<div id='divid'>{{ notification }}</div>
The problem here is that , I don't think its a good Idea to keep doing ajax calls like this every x seconds/minutes.
Is there a way to push updates from the backend as soon as a database is updated directly to the browser , without polling for updates like this ?
Or is django not made up for it ?

I guess you should have a look at django-comet or any othe comet-like project.
It will allow you to push a response from server to the user's browser.
Wiki page on Comet: http://en.wikipedia.org/wiki/Comet_(programming)
Also, let me share a link to a great answer on this topic: https://stackoverflow.com/a/4403209/2795926

Related

Best way to run script from several forms on my site

I'm very new to this and trying to figure out the best way to accomplish. I am using Shopify and have been trying to implement a script that runs upon account creation that redirects to my shop page and also subscribes them to my mail list. I have this code in my account.liquid file.
//if(document.referrer == "https://example.com/challenge" || document.referrer == "https://example.com"){
var url = "http://example.us10.list-manage.com/subscribe/post?u=48c8cbb03628105f109c9ea64&id=111111111"
var email = $('.email.note').html();
var path = "https://example.com/collections/all";
setTimeout( function() { window.location.href= path; }, 3000);
$.ajax({
type: "POST",
url: url,
data: {EMAIL : email},
dataType: 'jsonp',
});
//}
I currently have a form on my home page and also a popup that uses the same form in my shop page that both create a customer account. Before I commented out the document.referrer it worked properly only when there was a challenge, but without the challenge it did not work. Now commented out it will run properly, but will also run the script anytime a customer goes to their account page. I obviously only want it to run once upon account creation.
I have a feeling there is a better way to accomplish this and have spent hours searching, but haven't found anything.

Set ajax call only when the new record inserted to database

I wants to get updated comment from chat list to the page without refreshing the page, Thats I have used ajax call for the list but I have to call this function for every 5 seconds to check whether new chat is inserted or not to the database,
$(document).ready(function(){
setInterval(function(){
$.ajax({
type:'POST',
url: baseUrl+"chat",
cache: false,
data: dataString,
crossDomain: true,
success: function(data){
var getData = JSON.parse(data);
if(getData.status == "success")
{
for(i=0;i<getData.chat.length)
{
$("chatList").text("");
$("chatList").append("<span class='black'>"+getData["chat"][i].name+" : <span class='blue'>"+getData["chat"][i].comment+"</span>");
}
}
else
{
alert(getData.message);
}
}
});
},5000);
});
So I wants to know if there is any easy way to do this or from PHP MySQL it is possible to send page a new comment inserted notification ?
Best practice is to use HTML5 WEB WORKERS.
HTML5 Web Workers
The problem with JavaScript on the browser is that it runs on a single thread. In other words, two scripts or processes cannot run simultaneously. If you are processing JavaScript after page load, the end user cannot interact dynamically with the page. The JavaScript will not handle UI events while processing something else. If you process something large before page load, the end user has to wait all-together which is a horrible user experience.
You can use a websocket, socket.io for example. That will allow you to send notifications from the server to the client.
So, when you recieve data from your chat (cient) in your API (server), after updating the database, you will have to send a 'notification' to your client.
When your client get the notification, you can make your AJAX call :
socket.on('notification', function(){
doYourAJAXStuff();
});
You can use socket.io api to get real-time information to the client..

Stackoverflow, Linkedin like notification when there is new activity

Lots of site have notification system when there is new posts.
For example,
in stackoverflow
in LinkedIn
When this is clicked the page reloads.
I wanted to implement this kind of system in my application.
So when new items are added in database, show this kind of notification, and when user clicks it. Reload the page.
Does anyone have idea of how this kind of notification works and how we can implement it?
Any post or idea regarding this would be helpful.
Also, If someone thinks this question can have more tags, feel free to add.
Here is the quick idea how you can do this.
Client side auto refresh and get content using ajax post.
<h2>Notification</h2>
<div id="divNotif" style="display:none;"></div>
<script id="sessionJs" type="text/javascript">
function GetNotification() {
$.ajax({
type: "GET",
url: '#Url.Action("GetNotification", "Notification")',
dataType: "html",
success: function (data) {
$("#divNotif").html(data);
$("#divNotif").fadeIn('slow');
setTimeout(function () { GetNotification(); }, 5000); //change timeout duration here
},
error: function (data) {
//alert("BAD:" + data.statusText);
}
});
}
GetNotification();
</script>
Controller return json
[HttpPost]
public ActionResult GetNotification()
{
int notifCount = fromDb.NotificationCount;
return Content("<span>New notification " + notifCount + "</span>", "text/html"); // returning a PartialView would be better one
}
Ashwini Vermas answer uses polling instead of pub/sub. It will increase trafic and put strain on the web server etc. Use SignalR instead.
I would publish all system events on a message bus then clients can subscribe to them using this library
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy
Here is a demo
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/tree/master/SignalR.EventAggregatorProxy.Demo.MVC4
disclamier: I'm the author of the library

Ajax Login With PHP Issue

I am creating A login system using AJAX,PHP & SQL obviously.
Anyway I am trying to implement A real time login feature so it will log the user in without refreshing the page.
I have done that almost but the only issue when the user clicks remember me that uses cookies instead of sessions but the JQuery isn't proccessing that?
I want it to detect depending if it was checked ether remember the user or not it only starts a session, when it does register a cookie the logout page is not deleting the cookie which he did before i added the jquery code in so nothing on the php end and I am mainly A PHP Developer and still learning.
(I cannot post the server side code for privacy reasons as I be using this in A project
but it looks similar to any other normal php login script)
Here's the JQuery
function validLogin(){
var user_login=$('#user_login').val();
var user_pass=$('#user_pass').val();
var remember_me=$('#remember_me');
var dataString = 'user_login='+ user_login + '&user_pass='+ user_pass;
$("#flash").show();
$("#flash").fadeIn(100).html('Loading..');
$.ajax({
type: "POST",
url: "ajax/procces.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
$("#flash").hide();
if(result=='correct'){
window.location='index.php';
}else{
$("#errorMessage").html(result);
}
}
});
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
Thanks
You don't pass your variable 'remember me' to your ajax request. For instance :
data: {login: user_login, passwd: user_pass, rememberMe: remember_me}
Another point, be careful you treat information from client-side. Never trust the client. Test all your values in PHP.

AJAX Load Content

Im completely lost on how to work AJAX. Looked up some tutorials and all seemed pretty confusing. I ran into the problem: [ Script only runs once ].
I would use it to reload pages like so: [ http://www.roblox.com/Poison-Horns-item?id=62152671 ] so I could get the latest item prices, without refreshing the page. if anyone could help/tell/point me in the right direction, it'd help TONS.
Im somewhat a beginner scripter, so be a little patient ;)
Thanks for any help,
Alex
AJAX requests are the same as page requests (GET and POST), except that they are handled asynchronously and without leaving the current page. The response data is the source of the page you wanted to fetch. That source is useless until you parse/use it.
A simple jQuery example:
//for example, we are on example.com
$.ajax({
type : 'get', //the METHOD of the request, like the method of the form
url : 'index.php' //the url to fetch
data : { //additional data which is synonymous to:
query1 : 'foo', // - url queries
query2 : 'bar', // - form inputs
query3 : 'baz',
},
success : function(resposeText){ //response text is the raw source of the fetched resource
$(element).html(responseText); //use response as HTML for element
}
});
//this is similar to requesting:
http://example.com/index.php?query1=foo&query2=bar&query3=baz
agree with joseph. You can use ajax by javascript manner or by jQuery, I personally suggest jQuery because it is simple to implement.
$.ajax({
type: 'GET',
url: "URL you want to call" ,
data: 'Data you want to pass to above URL',
cache: true, //to enable cache in browser
timeout: 3000, // sets timeout to 3 seconds
beforeSend: function() {
//when ur ajax call generate then u can set here loading spinner
},
error: function(){
// will fire when timeout is reached
},
success: function(response){
//in response you can get your response data from above called url.
}
});

Categories

Resources