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
Related
I'm trying to work on a clickable DIV from some vertical tab panel. What I want is when clicking on a specific DIV call a static method to do some tasks, so I did this:
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li onclick="myEvent()">Tuttle</li>
then, my JavaScript code:
<script>
function clickEvet() {
alert("alert test message");
#MyProject.myMethod()
}
</script>
Calling the function "clickEvent()" works. The problem is that #MyProject.myMethod() is called no matter what, in other words, #MyProject.myMethod() is being executed as soon the page loads. I want it only when I click on my div.
This is from a cshtml file and I'm using .net 4.5
SOLUTION:
I'm editing my question to post the answer for future references...:
Thanks to other comments I finally understood how to work with Ajax and make it work. Here is the solution:
<script>
function vaxGUID() {
$.ajax({
type: 'POST',
url: "/VAXBean/bmx",
data: '{"Name":"AA"}',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
success: function (data) {
bmx = "http://www.vitalbmx.com";
$('a.varURL').attr('href', bmx);
GUID = data;
alert("Good response - " + data + " - " + bmx);
},
error: function (data, success, error) {
alert("Error : " + error);
}
});
return false;
}
</script>
With this Ajax method I'm making the call to some static method in the background
I want it only when I click on my div. <= When you click on the DIV that is being done in the browser after the request has been sent. There is no way for the browser to call directly back inside a method in your application. The HTML has already been generated and sent by the server in the request to the client and that is where that communication cycle stops.
If you want a click (or any other event) to do something specifically on the server you need to do one of these standard actions that are used to communicate back to the server.
Create an AJAX request back to your MVC Controller to get data (or whatever).
Create a link (standard url)
Create a form post back
And of course the #MyProject.myMethod() executes every time your page is rendered because your razor view is a code file that is being interpreted line by line so it can be rendered and sent to the client that requested it. What would be valid here is if myMethod output some javascript or something that the browser could understand and do something with, that is what would be expected.
You can't do it. All # (Razor) expressions is resolved during page rendering on server. That's why you method is called.
Probably, you need to make an Ajax call.
Look for a more detailed explanation here:
How do I call a static method on my ASP.Net page, from Javascript?
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..
My boss asked me today if it is possible to use Sharepoint list data into an external HTML website...
The client have a sharepoint intranet and an HTML website.
They are publishing news on their sharepoint but they'd like to recover the news (sharepoint list) and put them into the home page of the other website.
I saw some different possibilities using Jquery or JavaScript or else Json.
To the effect that i'm not a regular with these languages...
First question: Is that possible? Because i think the two websites have differents servers.
Second one: if yes, how can i do that?
Thanks in advance
Hello and welcome to stackoverflow. A better place for your question might be over at https://sharepoint.stackexchange.com/.
Anyways, you can of course use a variety of methods to get sharepoint's list data - for example using the REST interface:
function getListItem(url, listname, id, complete, failure) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data);
},
error: function (data) {
failure(data);
}
});
}
}
Here's some more info:
http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
Yes, that is very much possible. You can consume webservices in sharepoint to expose data.
If you other server is purely HTML then the only way would be to go with consuming web services via Jquery.
However, if its PHP/Ruby or some other server, you can consume the services in the server side language as well.
https://www.nothingbutsharepoint.com/sites/devwiki/articles/pages/got-rest-querying-sharepoint-list-data-using-rest-services-client-side-part-1.aspx
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
I am developing a web application and am using jQuery to provide a good user interface for users. Therefore, I am using ajax requests and many jQuery functions.
If I disable JavaScript in the browser most of the function will not work because I am sending asynchronous ajax requests for many functions. But how can I handle this? Do I need to rewrite the code without using jQuery and ajax?
Find a below a sample button click event:
$("#renameCategory").live('click', function (event) {
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: '#Url.Action("UpdateCategoryName", "Category")',
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
How can I handle this?
Ajax requests and jQuery will not work when the client has JavaScript disabled. The best way to make this work is to use the URL from the <a> tag href like so:
Click Me!
$("#renameCategory").on('click', function (evt) {
//To prevent the link from sending the default request
//call preventDefault() on the jQuery event object
evt.preventDefault();
//
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
//GET THE URL FOR THE AJAX REQUEST
var actionUrl = $(this).attr('href');
//
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: actionUrl,
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
You will also need to check for ajax requests in your Controller like below:
public ActionResult UpdateCategoryName() {
...
if(Request.IsAjaxRequest()) {
return Json(yourData);
}
return View();
}
This way, if your user has JavaScript disabled, the link will function like a normal HTTP request. If the user has JavaScript enabled, then they will get the Ajax experience. This is called graceful degradation.
Ajax call works when javascript is enabled.
You can handle it by server-side scripting, when javascript is disabled, you must do works by post/get requests, so you have to recode your web application.
If a lot of modification is needed for your website to work without javascript, then just force the users to enable javascript. One way to notify users to enable javascript is to use the noscript tag. http://www.w3schools.com/tags/tag_noscript.asp
View stackoverflow's page source to see how they use noscript
If JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code. The most common way to implement interactive web application other than Javascript is Flash, so you can still have a backup plan. You can also go with the old-school server side only generated dynamic pages.
Today, however it is very rare for someone not to have JavaScript enabled, so it should not be an issue at all.
Anyway you can make use of the <noscript> html tag to display a message to these users.
<script type="text/javascript">
... Js code ...
</script>
<noscript>You have JavaScript disabled in your browser. Please enable it.</noscript>
Obviously any functionality depending on script will not work if scripting is disabled, not available or incompatible with the environment it is trying to run in.
It is considered by many to be a good strategy to develop web applications so that they work without script support. You can then add scripting to improve the workflow and efficiency, but you will do so knowing that you have a fall back to a working system available if at any point the script should not run.
The discipline of designing and implementing a good workflow based on just HTML and forms may well lead to an easier interface to script and a more efficient workflow.
All too often developers throw together some minimal HTML and CSS, then try and do everything in script. The extreme is to have a DOCTYPE, title element, one block element and one script element that does everything. Not recommended.