How to grab data using fetch() API POST method in PHP?

后端 未结 3 1515
野的像风
野的像风 2021-02-02 00:42

I am trying to use fetch() API POST method in order to grab the POST data in PHP.

Here is what I have tried:

var x = \"hello\";
fetch(url,{m         


        
相关标签:
3条回答
  • 2021-02-02 01:00

    Appearently, when using the Fetch API to send data to a PHP server, you'll have to handle the request a little different from what you're used to.

    The data you're "POSTing" or "GETting" is not going to be available in the super global variables since this input is not coming from a multipart-data form or an application/x-www-form-urlencoded

    You can get your data by reading the special file: php://input, for example using file_get_contents('php://input') and then try to decode that input with json_decode().

    Hopefully it helps.

    You cand read more about it here:

    https://codepen.io/dericksozo/post/fetch-api-json-php

    0 讨论(0)
  • 2021-02-02 01:05

    It depends:

    If you want to $_GET['x'], you need to send the data in the querystring:

    var url = '/your/url?x=hello';
    
    fetch(url)
    .then(function (response) {
      return response.text();
    })
    .then(function (body) {
      console.log(body);
    });
    

    If you want to $_POST['x'], you need to send the data as FormData:

    var url = '/your/url';
    var formData = new FormData();
    formData.append('x', 'hello');
    
    fetch(url, { method: 'POST', body: formData })
    .then(function (response) {
      return response.text();
    })
    .then(function (body) {
      console.log(body);
    });
    
    0 讨论(0)
  • 2021-02-02 01:20

    I use the postData function from MDN:

    /**
     * send_body___receive_response.js
     *
     * Can of-course be in <script> tags in HTML or PHP
     */
    
    async function postData( url='', data={ } ) {
      // *starred options in comments are default values
      const response = await fetch(
        url,
        {
          method: "POST", // *GET, POST, PUT, DELETE, etc.
          mode: "same-origin", // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          credentials: "same-origin", // include, *same-origin, omit
          headers: {
            "Content-Type": "application/json",  // sent request
            "Accept":       "application/json"   // expected data sent back
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
          body: JSON.stringify( data ), // body data type must match "Content-Type" header
        },
      );
    
      return response.json( ); // parses JSON response into native JavaScript objects
    }
    
    const data = {
      'key1': 'value1',
      'key2': 'value2'
    };
    
    postData( 'receive_body___send_response.php', JSON.stringify( data ) )
      .then( response => {
        // Manipulate response here
        console.log( "response: ", response ); // JSON data parsed by `data.json()` call
        // In this case where I send entire $decoded from PHP you could arbitrarily use this
        console.log( "response.data: ", JSON.parse( response.data ) );
      } );
    

    You could just POST data but I like to receive a response that it was successful.

    /**
     * receive_body___send_response.php
     */
    $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
    
    // Set initial response
    $response = [
      'value' => 0,
      'error' => 'Nothing happened',
      'data' => null,
    ];
    
    if ($contentType === "application/json") {
    
      // Receive the RAW post data.
      $content = trim(file_get_contents("php://input"));
    
      // $decoded can be used the same as you would use $_POST in $.ajax
      $decoded = json_decode($content, true);
      
      if(! is_array($decoded)) {
        // NOTE: Sometimes for some reason I have to add the next line as well
        /* $decoded = json_decode($decoded, true); */
    
        // Do something with received data and include it in reponse
        /* perhaps database manipulation here */
        $response['data'] = $decoded;
    
        // Success
        $response['value'] = 1;
        $response['error'] = null;
      } else {
        // The JSON is invalid.
        $response['error'] = 'Received JSON is improperly formatted';
      }
    } else {
      // Content-Type is incorrect
      $response['error'] =  'Content-Type is not set as "application/json"';
    }
    
    // echo response for fetch API
    echo json_encode($response);
    
    0 讨论(0)
提交回复
热议问题