Why when sending data using fetch, they do not come in PHP?

  • 0
    I send a string to the server using fetch using the POST method, but on the server (PHP) there is nothing in the global array _POST, and as a result, an empty array is returned (code from PHP: print_r ($ _ REQUEST);).
    let fetchStr = await fetch(`server.php`, {
            method: "POST",
            headers:{
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({str: content})//пробовал и просто строку, разумеется меняя headers, и как сейчас, json, ничего не работает.
          })

    Can you please tell me what is wrong here and how can I fix it?
    JavaScript Adeline Solomon, Jun 24, 2020

  • 2 Answers
  • 0
    Documentation:



    $ _POST - HTTP POST Variables

    An associative array of data passed to the script via HTTP by the POST method when using application / x-www-form-urlencoded or multipart / form-data in the Content-Type header of an HTTP request.


    And you have application / json, respectively, just take the input unparsed data.
    Anonymous

  • 0
    you send application / json

    if you want to receive application / json data, then on the server process it like this:



    $data = json_decode(file_get_contents("php://input"),true)

    $str = $data['str']
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!