The problem is that you don’t understand the difference between JSON and HTML or TEXT, this is the least you have to study before trying to use these formats.
That echo "SUCCESS";
prints this in the reply to the request SUCCESS
, this is not JSON, JSON has a format like:
{ "response": "SUCCESS" }
And the header (header) should be UTF-8 (of course you can use other charset types, but the default is UTF-8 for this case) when using json, so PHP should look like this:
<?php
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array( 'response' => 'SUCCESS' ));
The function json_encode
does not magically transform strings into JSON, it just converts strings into an accepted format within JSON values, i.e.:
- Quotes (
"
) in \"
- And accents like
ã
in \u00e3
Now using an array as I did in the example will work.
For their uses of header
as header("200 SUCCESS");
also note that you do not understand or still do not understand well how HTTP works.
HTTP stands for Hypertext Transfer Protocol which means "Hypertext Transfer Protocol". It is a communication protocol between information systems that allows the transfer of data between computer networks, mainly in the World Wide Web (Internet).
It communicates through Requisition and Answer, or the client (can be a browser or another server) makes a requisition to a server and this server returns a reply.
So much Requisition how much Answer are usually composed of header and body, except GET and HEAD requests, or responses to HEAD requests (has more types of requests but is not the focus to quote them yet).
An example of a request the client makes to a server:
Header:
GET /questions/130929/enviar-resposta-de-notificação-pelo-php HTTP/1.0
Accept: text/html,application/xhtml+xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.8
Cache-Control: max-age=0
Connection: keep-alive
Host: pt.stacokverflow.com
User-Agent: Mozilla/5.0 (Identificação do navegador)
In the case of GET has no "body"
And that the server sends for answer above may be something similar to this:
HTTP/1.0 200 OK
Date: Sat, 28 May 2016 22:03:54 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 17736
Connection: keep-alive
Vary: Accept-Encoding
<html>
...
</html>
See that the header goes from HTTP/1.0 (or 1.1) to the line break that comes after the Vary: Accept-Encoding
and the body comes after this line break, where begins the <html>
(of course there may be other line breaks or other type of content, but still it would be the BODY).
A basic scope of how the request and response works in HTTP:
Using in PHP, the 'header' function in PHP should always come before echo
, print
, var_dump
or any content that goes to "output" in the body of the HTTP response (except if using ob_start
), never afterwards, if this does not cause failure, or if errors are turned off this will only cause part of the response to be sent and the default server headers will be sent instead of your own.
Almost all your tests are totally wrong,
There is no "header" or "Verb" called 200 SUCCESS
:
//erro 3
header("200 SUCCESS");
return "200 SUCCESS";
return
is not the same thing as echo and does not serve to send content to answer:
//erro 5
header('Content-Type: application/json');
return 'SUCCESS';
There is no "header" or "Verb" called SUCCESS
:
//erro 6
header('Content-Type: application/json');
header('SUCCESS');
In addition to the first header is missing a part the function result
there is no:
///erro 9
header("HTTP/1.1 200");
header("Content-Type:application/json; charset=utf-8");
result 'SUCCESS';
No "body" data passed in "header":
///erro 7
header('Content-Type: application/json');
$success =json_encode('SUCCESS');
header($success);
These are almost correct, but lacked the "body" and there is no header or Verb like this HTTP/1.1 200 SUCCESS
///erro 8
header("HTTP/1.1 200 SUCCESS");
header("Content-Type:application/json; charset=utf-8");
And in this:
//erro 10
header("Content-Type:application/json;");
header('HTTP/1.0 200 SUCCESS');
In HTTP as I said 200 is default, but if you have another header that has affected the default then you can use the header function like this:
header("Content-Type: application/json; charset=utf-8", false, 200);
However, if you only want to change the status code then this would be correct:
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
header($protocol.' 200 OK');
Or on PHP5.4:
http_response_code(200);
Summarized the correct is HTTP/1.1 200 OK
for status 200, if you want other status codes see the following links.
List of HTTP codes
Your problem is not quite HTTP, but it’s still good to learn which are the correct status codes, follow two links to study:
Where is the problem then?
About your problem, of sending the answer 200, it is already standard on the server, what should be occurring is that you are using jQuery, as $.ajax
or $.get
or $.post
and the answer is yes coming as 200, but json is in an invalid format (as I quoted at the beginning of the answer), this makes the "PARSE" jQuery fails, then always error occurs.
Then your PHP should look like this:
<?php
header('Content-Type: application/json; charset=UTF-8');
//Funções MYSQL
echo json_encode($data);
?>
Of course if you want to send a status code in case of an error in PHP you can try using ob_start
, so you can use the header function after echo
, would look like this:
<?php
ob_start();
header('Content-Type: application/json; charset=UTF-8');
if (... EXECUTA A QUERY MYSQL ...) {
$resposta = 'success';
} else {
$resposta = 'error';
}
echo json_encode(array( 'response' => $resposta ));
And Jquery must be something like this:
$.ajax({
type: "POST",
url: '[SUA PÁGINA PHP].php',
data: { "DADOS DO POST": "VALOR A SER ENVIADO" },
dataType: "json" //IMPORTANTE
}).done(function(data) {
alert(data.response);//response é o mesmo que foi enviado no json_encode
}).fail(function(jqXHR, textStatus, errorThrown) {
alert( "error:" + textStatus );
});
Documentation
Avoid "shooting in the dark", I recommend to always look at the documentation before using a function, follow the links to the documentation to study:
The problem is that you don’t seem to understand the difference between header and body within the HTTP structure and don’t understand the difference between JSON and other formats
– Guilherme Nascimento
Okay, William I don’t really know much about html. So, please, you teach me to make in php a simple response to a json request that works?
– prmas
If you have time on Monday I’ll explain what json, html and http is
– Guilherme Nascimento
Are you "serto", do not know the answer and still want to humiliate others? Unfortunate!!!! If you knew the answer would post here....
– prmas
Friend you are mistaken and your attitude is totally disrespectful, I suggest you try to behave or I will have to report the situation, ok I am in the middle of a job trying to finish to enjoy the little time I have on the weekend but I will answer. Now to return to this type of situation unfortunately I will have to report. Understand? Wait I am providing an answer to your doubt. Meanwhile READ: http://answall.com/help/be-nice if you don’t actually read it pitiful!
– Guilherme Nascimento
@prmas avoids quick judgments. We are all here to share solutions and knowledge about programming. You ended up getting a very good answer from Guilherme.
– Sergio