0

I'm working on a project where I have an async function in JS calling to a PHP function, but for some reason it keeps throwing my error function even though I feel I have the syntax correct.

Here is the JS:

async function UpdateBlog() {
    var test = "test";
    const settings = {
        method: 'POST',
        body: JSON.stringify({
            blog: test
        }),
        headers: {
            'Content-Type': 'application/json',
        }
    };
    var thisurl = baseurl;
    const response = await fetch(thisurl, settings);
    document.getElementById("scratch").innerHTML = await response.json();
}

And here is what is catching it in PHP

if ($_SERVER["REQUEST_METHOD"] == "POST"){
  if(isset($_POST["blog"])){
    UpdateBlog($_POST["blog"]);
  } 
  else {
    RequestFail();
  }

function RequestFail(){
  http_response_code(404);
  header('Content-Type: application/json');
  echo json_encode(false);
}

I have tested the "UpdateBlog" PHP function as a GET and it works, so that's not the issue

Edit: Figured out the first if... statement is being triggered, but it seems that $_POST["blog"] is showing up as empty

tanneryea
  • 11
  • 4
  • json is not loaded into the `$_POST` property as it is not a query string. To read json from a php request, you have to do it yourself. search engine around for how to read json request in PHP – Taplar Dec 03 '20 at 17:42
  • Does this answer your question? [How to retrieve Request Payload](https://stackoverflow.com/questions/9597052/how-to-retrieve-request-payload) – Taplar Dec 03 '20 at 17:44
  • Not really, no. The JS script is returning "false" through the RequestFail PHP method, so I'm not having an issue receiving the JSON. Likewise, when I tried it with GET I received the json fine. My issue is that it does not seem to be triggering the first if... statement – tanneryea Dec 03 '20 at 17:47
  • Clearly the conditional testing `isset($_POST["blog"]` is failing. The body of your post does not contain a property named `blog`. You either need to provide the property name in your body or decode the JSON at the server and _then_ determine if there is a `blog` property in the deserialized object. – Randy Casburn Dec 03 '20 at 17:55
  • The body does contain a property name "blog" - it's in the example – tanneryea Dec 03 '20 at 18:00

1 Answers1

0

If fetch is a "thenable" function, it may be better to use

const result = ''
fetch(thisurl, settings).then(
  (result) => {response = result;}
)