Answer the question
In order to leave comments, you need to log in
How to accept JSON response in PHP?
I send a request to the server via JQuery:
$.ajax({
type:'POST',
url:" https://server.ru ",
data: JSON.stringify
({
"id" : 5555,
"phone" : "79999999"
}),
success:function(data){
$("#error").html(JSON.stringify(data));
}
});
I receive a JSON.stringify(data) string in response , which I can output via JavaScript to a block with id="error" .
How can I get this response string in PHP?
Answer the question
In order to leave comments, you need to log in
JSON.stringify is not needed
$data = ['success' => false; 'message' => 'Тест', 'phone' => $_POST['phone']];
header('Content-Type: application/json');
echo json_encode($data);
$.ajax({
type: 'post',
url: '/script.php'. // без http:// и домена
dataType: 'json',
data: {id: 5555, phone: 4444},
success: function(data) {
if (!data.success) {
$("#error").html(data.message);
console.log(data.phone); // 4444
}
}
});
file_get_contents("php://input")
php.net/manual/en/wrappers.php.php#wrappers.php.input
You send data using the POST method, so you should accept it. $_POST
Look in the global variable .
PHP:
$id = $_POST['id'];//The value that comes with javascript.
$phone =$_POST['phone'];//The value that comes with javascript.
//then do what you want with it.
// Send this in response:
$data = "Response for js";
echo json_encode($data);
JS:
$.ajax({
url: '/',
method: 'POST',
timeout: 25000,
data: {
"id": "your value",
"phone": "your value"
},
success: function(data ) {
data = $.parseJSON(data);
$("
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question