September 2010 Archives

LinkedIn now has some fancy ajax stuff, so you can just click accept on an invitation, and instead of loading a page, it does a background request and, if all goes well, that invite just disappears with a success message, leaving you to deal with the next request without leaving the page.

That's great. I did a lot of that when doing web application work for DAZ3D. One of the hallmarks of efficient e-commerce is giving people tools to get things done faster - and that meant things like list filters, type-ahead searches, ajax'd add-to-cart buttons - you name it.

But LinkedIn has an issue. See the screenshot:

I've used Firebug to peek at what is happening when it makes the request. As you can see, there's an error. The first time, I wrote it off as something transient, but I came back days later and got the same error.

I decided to log off and log back on, and the issue was fixed. Clearly, the "remember me" was sufficient for a normal page view, but not sufficient for accepting a connection request.

The problem arises because the ajax request is getting a normal full pageview back with the 500 error. I've written before about detecting ajax; if you're going to send a request over ajax, then whatever is handling the request should be aware, even if it's an error. There's nothing wrong with a 500 code for an ajax request that errors out; but your javascript should be ready to handle it.

In this case, as you can see from the (slightly privacy-screened) screenshot, I had a "spinny" (that's the technical term) that was going to sit there forever. That's especially bad, as a normal user will have no idea if the request has failed or is taking a really long time. Ideally, you throw a good error to the user; or, in this case, since you're not accepting their stale credentials, even redirect them to a login box. What you don't do is just throw a 500 error the javascript can't interpret and then stop there.

I personally like returning JSON objects, and I prefer to return them regardless of the code: 200 or 500, you get JSON if you made an ajax request. Then, my javascript always "fails over" - it looks for success. If there's no success message, it's an error.

As you can see here, this code tests for a success message - using javascript's || operator to avoid any error messages being thrown to the user even if that element doesn't exist - and unless a success message is available, it prints an error. It tries to use the error returned by the server, if one exists - but again, if the error isn't there, it has a default message.

The point here is: don't leave your users hanging. (Also, you may not want to tell people your crack team is springing into action to handle a 500 error if that's not the case and it will still be failing days later, but that's aside from the point.)