😅Javascript Fetch JSON PHP Complete FormData phần 1(ok)

Đọc thêm: https://wordpress-lionel.gitbook.io/wordpress-advand/upload-image-form-how-to-integrate-ajax-file-upload-in-wordpress-use-submit-p2-ok

Một ví dụ hay đã sử dụng

C:\xampp82\htdocs\testvn\wp-content\themes\AstraChild\assets\js\admin-custom-script.js

var $ = jQuery;
$( document ).ready(function() {
  $('.mphb_sc_search-submit-button-wrapper .button').click(function(e) {
    e.preventDefault();
    const form = document.getElementById('mphb_sc_search_form');
    const fd = new FormData(form);
    fd.append('action', 'search_form_ajax');
    jQuery.ajax({
      type: 'POST',
      url: fiuajax.ajaxurl,
      data: fd,
      contentType: false,
      processData: false,
      success: function(response) {
        console.log(response);
      }
    });
  });
});

Ví dụ 1:

test.php

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<p id="before">This is the JSON before the fetch.</p>
	<p id="after">This is the JSON after the fetch.</p>
	<button type="button" onclick="myButtonClick()">Press Me</button>
	<script type="text/javascript" src="fetch.js"></script>
</body>
</html>

C:\xampp\htdocs\data\fetch.js

function success(json) {
  document.getElementById('after').innerHTML = "AFTER: " + JSON.stringify(json);
}
function failure(error) {
  document.getElementById('after').innerHTML = "ERROR: " + error;
}
function myButtonClick() {
  var url = 'json.php';
  var before = {
    foo: 'Hello World!'
  };
  document.getElementById('before').innerHTML = "BEFORE: " + JSON.stringify(before);
  fetch(url, { method: 'POST', body: JSON.stringify(before), headers: { 'Content-Type': 'application/json' } })
    .then(
      res => res.json()
    )
    .then(
      response => success(response)
    )
    .catch(
      error => failure(error)
    );
}

C:\xampp\htdocs\data\json.php

<?php
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
  $content = trim(file_get_contents("php://input"));
  $decoded = json_decode($content, true);
  $decoded['bar'] = "Hello World AGAIN!"; // Add some data to be returned.
  $reply = json_encode($decoded);
}
header("Content-Type: application/json; charset=UTF-8");
echo $reply;
?>

Ví dụ 2:

C:\xampp\htdocs\data\index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>PHP</title>
</head>
<body>
  <form action="handle_form.php"  method="GET" id="example_form">
    <label for="username">Username</label>
    <input type="text" name="username" id="username">
    <label for="favorite_number">Favorite number</label>
    <input type="number" name="favorite_number" id="favorite_number">
    <input type="submit" value="Skicka">
	</form>
  <script src="main.js"></script>
</body>
</html>

C:\xampp\htdocs\data\main.js

// Get the whole form, not the individual input-fields
const form = document.getElementById('example_form');

/**
 * Add an onclick-listener to the whole form, the callback-function
 * will always know what you have clicked and supply your function with
 * an event-object as first parameter, `addEventListener` creates this for us
 */
form.addEventListener('click', function(event){
    //Prevent the event from submitting the form, no redirect or page reload
    event.preventDefault();
    /**
     * If we want to use every input-value inside of the form we can call
     * `new FormData()` with the form we are submitting as an argument
     * This will create a body-object that PHP can read properly
     */
    const formattedFormData = new FormData(form);
    postData(formattedFormData);
});

async function postData(formattedFormData){
    /**
     * If we want to 'POST' something we need to change the `method` to 'POST'
     * 'POST' also expectes the request to send along values inside of `body`
     * so we must specify that property too. We use the earlier created 
     * FormData()-object and just pass it along.
     */
    const response = await fetch('handle_form.php',{
        method: 'POST',
        body: formattedFormData
    });
    /*
     * Because we are using `echo` inside of `handle_form.php` the response
     * will be a string and not JSON-data. Because of this we need to use
     * `response.text()` instead of `response.json()` to convert it to someting
     * that JavaScript understands
     */
    const data = await response.text();
    //This should now print out the values that we sent to the backend-side
    console.log(data);
}

C:\xampp\htdocs\data\handle_form.php

<?php
if(isset($_POST)) {
	echo $_POST["username"];
	echo $_POST["favorite_number"];
}

Ví dụ 3:

FormData được sử dụng khi máy chủ dự kiến nhận dữ liệu ở dạng x-www-form-urlencoded Điều này không phải lúc nào cũng đúng, một số máy chủ muốn bạn gửi dữ liệu dưới dạng đối tượng JSON. Điều này có nghĩa là chúng ta phải thực hiện một số thay đổi đối với cả giao diện người dùng và phụ trợ.

C:\xampp\htdocs\data\index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>PHP</title>
</head>
<body>
  <form action="handle_form.php"  method="GET" id="example_form">
    <label for="username">Username</label>
    <input type="text" name="username" id="username">
    <label for="favorite_number">Favorite number</label>
    <input type="number" name="favorite_number" id="favorite_number">
    <input type="submit" value="Skicka">
	</form>
  <script src="main.js"></script>
</body>
</html>

C:\xampp\htdocs\data\main.js

const form = document.getElementById('example_form');
form.addEventListener('click', function(event) {
  event.preventDefault();
  /*
   * There is no shortcut like with 'new FormData(this)', we need
   * to construct the form-object ourselves. We are creating a regular
   * object instead of a FormData-object. `this` refers to the form,
   * we could also write: form.username.value and form.favorite_number.value
   */
  const formattedFormData = {
    username: this.username.value,
    favorite_number: this.favorite_number.value
  }
  postData(formattedFormData);
});

async function postData(formattedFormData) {
  /**
   * The request is still 'POST' but the $_GET variable
   * will get values too: 'name' and 'favorite_color'
   */
  const response = await fetch(
    'handle_form.php', {
      method: 'POST',
      /*
       * We also need to stringify the values, turn the
       * JavaScript object to a single string that is accepted
       * as JSON. So we are sending one string that contains
       * all our values
       */
      body: JSON.stringify(formattedFormData)
    }
  );
  const data = await response.text();
  console.log(data);
}

C:\xampp\htdocs\data\handle_form.php

<?php
//inside of 'handle_form.php'

/* We are parsing all the data that is being sent as JSON. `json_decode`
 * turn our JSON-object into a PHP Associative array and stores it inside of
 * `$data`
 */
$data = json_decode(file_get_contents('php://input'), true);
echo $data["username"];
echo $data["favorite_number"];

Last updated