Unable to receive a response to the request by mail

This is my current Javascript code for sending requests every 5 minutes.

function sendRequest() {
    $(document).ready(function() {
        console.log($.post('../notify/notify.php', { notify: 1 }).done());
    });
}

setInterval(function() {
    console.log(sendRequest());
}, 5000);

When I then check the network in the developer tools, requests are sent and responses are returned as expected. This is my PHP code:

header('Content-Type: application/javascript');

if(isset($_POST['notify']) && $_POST['notfiy'] == "1") {
    echo json_encode(array(
        'Title' => 'Welcome to our Site',
        'Message' => 'You are current recieving notifications.',
        'Location' => 'http://example.com/',
        'State' => true
    ),true);
} else {
        echo json_encode(array(
        'State' => false
    ), true);
}

However, when I check the console, I see that it is a type Object {readyState: "1"}, and when I then expand it, the expected response is wrapped inside the field responseText. However, it console.log()returns undefined when I add .responseTextto the end $.post().done().

What am I doing wrong? How can I get a response from my PHP file?


Update:

, header(). /json /javascript. , , , , . function(param) done(), .

+4
3

?

console.log(), .responseText .responseJSON $.post() $.post() console.

console.log() , . console.log() jQuery. $.post()

, , , Object {readyState: "1"}

not .responseText .responseJSON jxXHR

: jqXHR

.done() , console.log() $.post(), . .responseText .responseJSON .done().

.done(function(data, textStatus, jqxhr) {
  console.log(data, jqxhr.responseJSON)
})

Content-Type headers php "application/javascript", echo a array php. headers "application/json". $.post() , Content-Type dataType; "json".

// declare variable `interval` for ability to call `clearInterval(interval)`
var interval; 
function sendRequest() {
    return $.post('../notify/notify.php', { notify: 1 }, "json")
    .done(function(data) {
      console.log(data)
    })
    // handle error
    .fail(function(jqxhr, textStatus, errorThrown) {
      console.log(errorThrown)
    });
}

$().ready(function() {
   sendRequest().then(function() {
     interval = setInterval(sendRequest, 5000);
   })
})
+2

console.log() undefined , sendRequest .

, done, - , returend:

.done(function(text) {
    console.log(text);
});
+1
$.post('../notify/notify.php', { notify: 1 },function(data){console.log(data);})
0
source

Source: https://habr.com/ru/post/1659996/


All Articles