3

Say, I make an ajax request to a server from a page, something like "show more articles". Is there a common agreement on the format or rather structure in which a result should be returned?

Something like this:

{articles: [{id: ..., title: ..., created_by: ...}, {id: ..., title: ..., created_by: ...}, {id: ..., title: ..., created_by: ...}]

Or

{result: "ok", data: [{id: ..., title: ..., created_by: ...}, {id: ..., title: ..., created_by: ...}, {id: ..., title: ..., created_by: ...}]

Or:

[{id: ..., title: ..., created_by: ...}, {id: ..., title: ..., created_by: ...}, {id: ..., title: ..., created_by: ...}]

Notice, I'm talking about ajax requests/responses, not REST API.

And also, what if an error has occurred? What's the structure of an ajax response containing information about an error?

2

As far as I know: no. There's no generic approach or standard.

Personally I make sure to always return an object, never a single value or array.

This ensures compatibility. For example, if I add a new field, existing code won't break and just ignore it instead.

As for error handling, I check whether there's an object property called error. If it's undefined, everything is fine. If it's a string, something went wrong.

1

It is much more important that your responses have a consistent structure among each other within your project than that they conform to any other project. This means that you can use generic code for communication, error handling, data formatting, perhaps sorting and filtering, etc.

If there were a de facto standard for the internal make-up of Ajax responses, it would make sense to follow it to make your project more understandable for any others who may have to deal with it. But since there isn't, you get to institute your own, and it's a goo idea to do so.

  • it's always important to be consistent in any project – Koodi Oct 24 '17 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.