M
M
MrSanta2017-10-31 01:22:51
PHP
MrSanta, 2017-10-31 01:22:51

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

4 answer(s)
A
Anton Mashletov, 2017-10-31
@mashletov

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
         } 
    }
});

A
Alexander Taratin, 2017-10-31
@Taraflex

file_get_contents("php://input")
php.net/manual/en/wrappers.php.php#wrappers.php.input

M
Morfeey, 2017-10-31
@Morfeey

You send data using the POST method, so you should accept it. $_POSTLook in the global variable .

D
Dima Tect, 2017-11-02
@Dima8249

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 question

Ask a Question

731 491 924 answers to any question