facebook type status and comment using ajax, jquery in asp.net mvc3 - ajax

i am working on status update and commenting application in asp.net mvc3 like Facebook wall and comment. User can comment my wall and all stuff like Facebook.
http://demos.99points.info/facebook_wallpost_system/
like above demo, i want to create my application.
how can i do that using mvc3 and ajax?
i successfully updated user status to database but cant get all status updates of same user, i want to use partial view to display all status of user below the status textarea.
and if user write some status and share status that time status message saved in database and again reflect to same view Asynchronously.
how can i do that using ajax?

I'm going to answer this in broad terms as I don't have any knowledge of asp.net or mvc3. However, it seems to me that you're looking for more architectural direction.
You will need to setup an endpoint which generates the status page, call it /status.asp. This will create the text area and load the existing status messages from your database.
Then create a second endpoint, say /api/status.asp. This is not a view, but an API in your application that let's a user create (and, if you want, retrieve/modify/delete?) a status.
When a user hits enter in the textarea, fire off an XHR request to /api/status.asp with the new status. It is common, but not required, to do this as a POST request (read up on REST - http://en.wikipedia.org/wiki/Representational_State_Transfer). This API should then save the new status to your DB, and return the uid of the status along with the status message, perhaps as JSON (or XML or YAML if you prefer, it's up to you). For example, in JSON:
{
status: [
{
uid: '1234567890987654321'
msg: 'Hello World'
}
]
}
(To send the XHR request it's easiest to use a JS library like Dojo ( http://dojotoolkit.org/reference-guide/dojo/xhr.html#dojo-xhr ) or JQuery ( http://api.jquery.com/jQuery.ajax/ ).)
When your XHR request returns, check the status is a 200 (everything went OK), then read the data returned. Write some Javascript to create a new DOM node, inject the status message into that DOM node and add it to the bottom of the previous status nodes.
Bonus Points:
If you want person B to be looking at person A's /status.asp page and for that page to auto-update when person A posts a new status, you'll need to do a little more work. Firstly, modify /api/status.asp to return a list of the last x (say, 10?) status updates when called via HTTP GET. Include the UID of each status along with the status text.
Call your /api/status.asp API repeatedly* (perhaps with a timestamp of the last time you called it, and get your API to only return status posts after that time), loop over the the results and check to see if that post is already included in the users page (perhaps by having an id on each DOM node matching the UID of the status). If not, add it to the page.
*you have a number of options for doing this. For example, simply setup a JS timeout (easy, but not very efficient), or use Comet (eg http://cometd.org/) or WebSockets ( http://websocket.org/ ). I'd go for a timeout first, get it working and then figure out if a better technology is required.

Related

Which http status codes to use when processing http post?

I have a HTML form, which I submit via http post.
There are two cases:
Case 1: The data is valid and data on the server will be updated accordingly
Case 2: The data is invalid and the http response contains an error message for the user.
Which http status codes should be used for each case?
I use htmx to submit the form. This means I don't need to use the POST/Redirect/GET pattern.
This question is not about JSON-APIs.
The complete list of HTTP response codes published by the Mozilla Foundation is pretty comprehensive and easy-to-read, so I'd recommend always consulting it as a guide. For the generic use-cases mentioned by you, there are a couple of different codes you can return - depending on what happens with the data on the server, and what you want to happen in the user's browser.
CASE 1: data is valid, data on server is updated
Base on your short description, the different status codes that might be applicable are:
200 (OK): you are updating an existing record on your own server - eg., the user is submitting a form which updates their existing contact information on your website - and information was received, and the record updated successfully. The response would usually contain a copy of the updated record.
201 (Created): you are not updating an existing record, but rather, creating a new record on your server - eg., your user is adding a new phone number to their contact details, which is saved in your database as a separate 'phone' record. The response should contain a copy of the newly created record.
205 (Reset Content): the same as 200, but implies that the browser view needs to be refreshed. This is useful when the record that is being updated has values that are dynamically calculated by the server, and which might change automatically depending on the values you're submitting. For example, if you have a user adding extra information to their online profile, which might grant them special status, badges and privileges on the website. This means, that if the user is viewing their profile information, that information will need to be updated with the new 'status' automatically granted by the server. The 205 response body will normally be empty, which means that to update the browser view your response-handling code will need to:
do further ajax requests and update the relevant part(s) of your
interface with new information from the server, or
redirect the user to a new URL, or
reload the entire page.
If working with HTMX, a 200 or 201 response would include the actual html snippet of the record that you want updated on the page - and HTMX will replace it automatically for you when it receives the response. With a 205 response, you could send an HX-Trigger response header that would call a custom event on the interface elements that need to update themselves - see the examples in the docs.
CASE 2: data is invalid, data on server is not updated
The status code that needs to be returned in case of an error varies depending on what caused the error. Errors that the server believes are the responsibility of the client - such as 'sending invalid data' - have a status code in the 4XX range. Some of the common errors in that range include 404 ('Not Found'), 403 ('Forbidden'), and 'Unauthorised' (401).
In the case of a client sending data that the server cannot process because it is 'not valid' - either because the request itself is malformed, or because the data doesn't pass some business validation logic - the current advice is to return status 400 (Bad Request).
Many years ago, some people believed that the status code 400 should only be used to indicate a malformed request (syntactical error) - not to indicate a failure in business validation logic (semantic error). There was a lot of debate, and temporarily a new status code (422) was created, that was supposed to cover semantic errors, exclusively. In 2014, however, the official definition of the status 400 code was changed to allow for the inclusion of both syntactical and semantical errors - which rendered status 422 essentially unnecessary.
You can find lots of discussions and explanations online about the differences between 400 and 422, and some people still argue passionately about this to this day. In practice, however, the 400 code is all you'll need - and you can include a response body in it that explains in detail, if needed, the cause of the error.
Note that when working with HTMX, a response with a 400 code should trigger an htmx:responseError event automatically. You can trap that event, for example, to update your form interface elements, in case of data validation errors caught by the server.
Well, 200 OK and 201 Created are the best for successful result.
For invalid data I would return 422 Unprocessable Entity, because the headers are correct, but body is not (though parseable by the server). The caveat is some HTTP clients won't handle 422 properly and in this case you have to use 400 Bad Request, however, the most of the modern clients will be fine.
You have said it is not about JSON APIs, but how will you meet this type of requirement - it is not clear whether this is relevant for your scenario???
SERVER DRIVEN BEHAVIOUR
I cannot see how a client could ever decide an HTTP status code based on input data. How would the client deal with these examples?
The call is not authenticated (cookie or token) - an API would return 401 - this tells the UI to perform a retry action.
The call is not authorized - an API would return 403 or 404 and the UI would present an error display.
The data is malformed or invalid according to domain specific checks - an API would return 400 and tell the UI what is wrong so that it can perform actions.
Something went wrong in server processing, eg data cannot be saved because database is down.
MY THOUGHTS
htmx looks interesting but a key requirement before using it would be ensuring that htmx can read server side error responses and use values returned. Maybe there is an elegant way to do this ...
Maybe I am just paranoid :). But it is worth being careful when choosing technologies that there are no blocking issues. Lack of error handlng control would be a blocking issue in most systems.
I'm using htmx 1.8 with asp.net core 6.0.
This works for me.
controller:
//server side validation failed
Response.StatusCode = 422;
return PartialView("Core", product);
client side javascript:
document.body.addEventListener('htmx:beforeOnLoad', function (evt) {
if (evt.detail.xhr.status === 422) {
//
// allow 422 responses to swap as we are using this as a signal that
// a form was submitted with bad data and want to rerender with the
// error messages
//
evt.detail.shouldSwap = true;
evt.detail.isError = false;
}
});
200 OK or 201 Created are the best choice for a successful POST request.
However, for invald data, you can pass 415 Unsupported Media Type

How to redirect with expressjs for a specific status?

I'm doing a blog-app currently, and I'm struggling to find a way to redirect/send a specific status and then act accordingly.
For example, I have a function that saves data in mongodb using mongoose. Then if no errors occurred 200 status.
newArticle.save(function(err){
if (err) throw err;
else {
res.sendStatus(200);
}
});
I want to be able to "fetch" this status (I'm using react for my views and routes and superagent for my ajax request), and then do something, for example, If my article is successfully added then load a certain component on the page that will have an h1 saying : Great job on posting an article.
So this is the first part.
The second part is, for everything 404 or 500 errors I want express to redirect me from for example : myblog.com -> myblog.com/something and then with my react router simply render some basic 404 pages, I do not know how to do that, I'm searching a lot and couldn't find something...
And, since I lack knowledge in the HTTP basics like how server and client talk to each other, if you have any good article/books to recommend I'd like to know about.
For first part. Depending on if you are using state or data library like flux or redux, if not, you can just have ajax response will have the HTTP status from your server. Using that, you can use setState to set a state property called something like isArticleSaveSucessful. Then simply render your success message component if that key is true.
Second part. For the better user experience which is I think what you intended, the url should still be what the user intended, ie, blog.com/bad-article-name but the page should render a 404. Very similar to above, when the API response comes back, setState accordingly, something like articleNotFound. Then in your render function, do an if check on the the state and if it is true, then render your error component.

Is it appropriate to use HTTP status codes for non-HTTP errors?

I know someone who is writing an API, and wants to use HTTP status codes to report the outcome of queries. e.g. if the user calls example.com/api/product_info?product_id=X, and the product doesn't exist, it would return HTTP status 400: Bad Request. I think that, since this is a valid call (i.e. the actual HTTP request is not malformed), it should return a 200 code response, and just have the body of the response something like {status: 'error'; message: 'No such product'}.
So my question is,
1) Is it appropriate to use HTTP status codes to convey non-HTTP program state, as in the example above?
2) Is there some standard, or at least widely used, specification describing when HTTP status codes are appropriate for use?
I was actually just talking about this the other day - http://blogs.mulesoft.org/api-best-practices-response-handling/
Your status code should reflect the response of the API, as 200 is "OK" and should be used for data that is successfully returned. However, 201 should be used for created items.
As mentioned already, in the event where the user tries a call but it fails (ie: users/?id=5) the server could return back a 400 to inform the user that it was a Bad Request, or a 404 if the resource doesn't exist.
It also depends on the action - if they are searching for a user and there are no responses, I wouldn't return an error, just a 200 with no results found. However, if they are trying to do a PUT or PATCH on a user that doesn't exist I would tell them with an error- as chances are there's a problem within their application somewhere.
In the link posted above you'll find more status codes, but one of the biggest advantages to using status codes is that it informs the client just though the header what actually happened with the server. This allows them to do a relatively quick (and low memory) check instead of having to deserialize the body and loop through an array looking for an errors key.
Essentially, you're giving them the tools to quickly and easily understand what is happening- something that I think every (sane) developer appreciates.
Hope this helps!
- Mike

Invoking a spring action repeatedly without user interaction

I Have a requirement like below :
Get invoked a particular action repeatedly without user interaction.For example, I have a message status page which displayed JMS message status.Message status can be changed by a number of application components.What I wanted is, my status UI has to pick latest message status.I need the action which displays status UI to be called repeatedly in an interval of 5 seconds or so, so that UI will get displayed with latest status.
How can I achieve this in spring.Is it something,Polling an action?
Any help highly appreciated
The easiest thing to do is to ask the server every few seconds using JavaScript and AJAX (pseudo-code using jquery):
function askServerForStatus() {
$.getJSON('/your-app/jms-status', function(response) {
$('#status').text(response.status);
}
}
setInterval(askServerForStatus, 5000); //every 5 seconds
Very simple example, it asks Spring MVC controllers mapped to /jms-status and expects the following JSON response:
{"status": "Processing..."}
Consider using setTimeout().
More general, reliable and robust approach is to use websockets, servlet-3.0 asynchronous support or comet. Also have a look at atmosphere.

How to Track the Online Status of Users of my WebSite?

I want to track users that are online at the moment.
The definition of being online is when they are on the index page of the website which
has the chat function.
So far, all I can think of is setting a cookie for the user and, when the cookie is found on the next visit, an ajax call is made to update a table with their username, their status online and the time.
Now my actual question is, how can I reliably turn their status to off when they leave
the website? The only thing I can think of is to set a predetermined amount of time of no user interaction and then set the status to off.
But what I really want is to keep the status on as long as they are on the site, with or without interaction, and only go to off when they leave the site.
Full Solution. Start-to-finish.
If you only want this working on the index.php page, you could send updates to the server asynchronously (AJAX-style) alerting the server that $_SESSION["userid"] is still online.
setInterval("update()", 10000); // Update every 10 seconds
function update() {
$.post("update.php"); // Sends request to update.php
}
Your update.php file would have a bit of code like this:
session_start();
if ($_SESSION["userid"])
updateUserStatus($_SESSION["userid"]);
This all assumes that you store your userid as a session-variable when users login to your website. The updateUserStatus() function is just a simple query, like the following:
UPDATE users
SET lastActiveTime = NOW()
WHERE userid = $userid
So that takes care of your storage. Now to retrieve the list of users who are "online." For this, you'll want another jQuery-call, and another setInterval() call:
setInterval("getList()", 10000) // Get users-online every 10 seconds
function getList() {
$.post("getList.php", function(list) {
$("listBox").html(list);
});
}
This function requests a bit of HTML form the server every 10 seconds. The getList.php page would look like this:
session_start();
if (!$_SESSION["userid"])
die; // Don't give the list to anybody not logged in
$users = getOnlineUsers(); /* Gets all users with lastActiveTime within the
last 1 minute */
$output = "<ul>";
foreach ($users as $user) {
$output .= "<li>".$user["userName"]."</li>";
}
$output .= "</ul>";
print $output;
That would output the following HTML:
<ul>
<li>Jonathan Sampson</li>
<li>Paolo Bergantino</li>
<li>John Skeet</li>
</ul>
That list is included in your jQuery variable named "list." Look back up into our last jQuery block and you'll see it there.
jQuery will take this list, and place it within a div having the classname of "listBox."
<div class="listBox"></div>
Hope this gets you going.
In the general case, there's no way to know when a user leaves your page.
But you can do things behind the scenes such that they load something from your server frequently while they're on the page, eg. by loading an <iframe> with some content that reloads every minute:
<meta http-equiv="refresh" content="60">
That will cause some small extra server load, but it will do what you want (if not to the second).
Well, how does the chat function work? Is it an ajax-based chat system?
Ajax-based chat systems work by the clients consistently hitting the chat server to see if there are any new messages in queue. If this is the case, you can update the user's online status either in a cookie or a PHP Session (assuming you are using PHP, of course). Then you can set the online timeout to be something slightly longer than the update frequency.
That is, if your chat system typically requests new messages from the server every 5 seconds, then you can assume that any user who hasn't sent a request for 10-15 seconds is no longer on the chat page.
If you are not using an ajax-based chat system (maybe Java or something), then you can still accomplish the same thing by adding an ajax request that goes out to the server periodically to establish whether or not the user is online.
I would not suggest storing this online status information in a database. Querying the database every couple of seconds to see who is online and who isn't is very resource intensive, especially if this is a large site. You should cache this information and operate on the cache (very fast) vs. the database (very slow by comparison).
The question is tagged as "jquery" - what about a javascript solution? Instead of meta/refresh you could use window.setInterval(), perform an ajax-request and provide something "useful" like e.g. an updated "who's online" list (if you consider that useful ;-))
I have not tried this, so take it with a grain of salt: Set an event handler for window.onunload that notifies the server when the user leaves the page. Some problems with this are 1.) the event won't fire if the browser or computer crashes, and 2.) if the user has two instances of the index page open and closes one, they will appear to logout unless you implement reference counting. On its own this is not robust, but combined with Jonathan's polling method, should allow you to have pretty good response time and larger intervals between updates.
The ultimate solution would be implementing something with websockets.

Resources