php return response json
Return HTML in PHP JSON response
I am building an app to save small notes and comments. The app will require from you to submit a title and it will provide you a text area for your text.
I was thinking to return the pair through JSON, but someone told me that this is bad practice.
Is it really bad practice to return HTML through Jason and why?
4 Answers 4
JSON (JavaScript Object Notation) is a lightweight data-interchange format http://www.json.org/
The HTML DOM structure should be created and use JSON for exchanging data.
Once you’ve retrieved the data creating dynamic dom elements is fair game.
A few closely related questions:
As far as I know, it’s not bad practice to return a HTML string within a JSON object. The accepted answer for that second question seems to agree:
Request and return JSON for large datasets, but include the (escaped) HTML snippet for each record in the JSON record. This means more rendering time and more bandwidth use than (2), but can reduce duplication of often complex HTML rendering.
JOSN was made to overcome the bulky XML format used for data exchanging. It really is a light weight data-exchange format as described by James. Suppose: You need to display a dynamic list of products having all the info related to a product. If you return full HTML in the JSON its size is 2048 characters. But if you only return product name and realted info without the HTML markup then the response text string size will be less than 2048 characters, it can be 100 characters only because you are omitting the HTML markup which is not really required. SO you can just have the light-weight version of the data and then insert it in the HTML markup using client side script. This will make your application faster because you will have to wait less for the server response as the data size is small and transferring small amount of data(characters) will always be quicker than large data(characters).
XML contained heavy markup therefore JSON was looked as an alternative for faster data transfer.
It really depends on how you plan to implement your idea. As you mentioned JSON, my best guess is you are trying to implement AJAX. Well, while it’s possible to return almost any type of content encoded as a JSON object, I don’t see why you would need to send HTML elements like text-area from the server through JSON. AJAX is used for scenarios where a server request is made and the client wants to get the response without refreshing the page from which the request was sent. The most common usage is username and password validation on login pages.
I think you should get a clear picture of server-side scripting and client-side scripting. What you have already implemented using jquery is known as client-side scripting and that’s exactly how it should be done. As for fetching data from PHP, that’s done when you need to read some data from the database residing on the server. Say, the text-area is displayed only if a valid title, that has an entry in the database, has been entered. And I don’t see any requirement of that here.
Возвращение JSON из PHP-скрипта
Я хочу вернуть JSON из скрипта PHP.
Я просто повторяю результат? Должен ли я установить Content-Type заголовок?
Решение
Хотя обычно с этим у вас все нормально, вы можете и должны установить заголовок Content-Type:
Если я не использую конкретную платформу, я обычно позволяю некоторым параметрам запроса изменять поведение вывода. Это может быть полезно, как правило, для быстрого устранения неполадок, чтобы не отправлять заголовок или иногда print_r полезную нагрузку данных, чтобы увидеть его (хотя в большинстве случаев это не должно быть необходимо).
Другие решения
Полный фрагмент красивого и понятного PHP-кода, возвращающего JSON:
Согласно руководство по json_encode метод может вернуть не строку (ложный):
Возвращает JSON-кодированную строку в случае успеха или FALSE на провал.
json_encode например, потерпит неудачу (и вернется false ) если его аргумент содержит строку, отличную от UTF-8.
Это условие ошибки должно быть зафиксировано в PHP, например, так:
Тогда принимающая сторона, конечно же, должна осознавать, что присутствие jsonError свойство указывает на состояние ошибки, которое оно должно соответственно обработать.
В рабочем режиме может быть лучше отправить клиенту только общий статус ошибки и записать более конкретные сообщения об ошибках для дальнейшего изучения.
Установите тип контента с помощью header(‘Content-type: application/json’); а затем повторить ваши данные.
Также полезно установить безопасность доступа — просто замените * доменом, к которому вы хотите получить доступ.
Тип носителя MIME для текста JSON:
применение / JSON.
так что если вы установите заголовок для этого типа и выведите строку JSON, это должно работать.
сделаю работу. но имейте в виду, что:
У Ajax не возникнет проблем с чтением json, даже если этот заголовок не используется, за исключением случаев, когда ваш json содержит некоторые HTML-теги. В этом случае вам нужно установить заголовок как application / json.
Убедитесь, что ваш файл не закодирован в UTF8-BOM. Этот формат добавляет символ в верхней части файла, поэтому ваш вызов header () не удастся.
Return JSON response from AJAX using jQuery and PHP
JSON stands for JavaScript Object Notation, it is a data-interchange format which is also been used to passing data from the server.
It is the best and effective way when need to return multiple values as a response from the PHP script to the jQuery.
You couldn’t directly return an array from AJAX, it must have converted in the valid format.
In this case, you can either use XML or JSON format.
In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.
On the basis of response show data in tabular format.
Contents
1. Table structure
I am using users table in the tutorial example.
2. Configuration
Create config.php for database configuration.
Completed Code
3. HTML
Create a