D
D
darksladen2017-04-19 15:52:04
API
darksladen, 2017-04-19 15:52:04

In what form it is better to give the data to the client?

Tell me how to correctly return data to the client upon request? I am writing an application in laravel, but I think it will be the same in other frameworks. Let's say I have a controller that has a method for adding an item to the cart.. What should it return to the client when requested? The request for it will obviously come through ajax ..
So far I have the following options:
- Return json with status and errors, if any, and process on the client
- Return a response status different from 200 (301) if the addition failed and process on client
- You can also give the finished view and display it in the modal, such as the product was successfully added and show it in the modal, for example ..
There are too many options .. Which one is better, why and what other options are there?
It is also not clear what such a method should do with a normal request, not through ajax. Do a redirect to the previous url or cart, for example?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
D3lphi, 2017-04-19
@darksladen

1) You need to give a json string with the response code / status, etc., so that you can process the response on the client side and perform the necessary actions.
2) We do not write any logic in the controller. It is moved to the service layer. (I'm talking about this phrase "there is a controller in which there is a method for adding goods to the cart").
3)
It's up to you to decide. It all depends on the need. Although, I would not adapt this route for a "normal request" at all, I would create another one specifically for this.

V
Vyacheslav Plisko, 2017-04-20
@AmdY

Give different headers and json with the required status field.
Some devices work crookedly with api without a body, so one header is not enough.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question