Get and Post method using Fetch API (ok)

https://www.geeksforgeeks.org/get-and-post-method-using-fetch-api/

Chú ý: Để nhận dữ liệu của Fetch thì chúng ta sử dụng

$json = file_get_contents('php://input'); chúng ta nhận được dưới dạng {"name":"lionel5","email":"lionel5@gmail.com","password":"123456"}

Chuyển đổi sang dụng đối tượng chúng ta dùng

$obj = json_decode($json, true); dưới dạng {name: "lionel4", email: "lionel4@gmail.com", password: "123456"}

Chúng ta xem ví dụ 2 để hiểu rõ.

Ví dụ 1:

C:\xampp\htdocs\register\some.json

{
  "name": "Lionel1",
  "email": "lionel1@gmail.com",
  "password": "123456"
}

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

<script>
	fetch('https://example.com/some.json')
  .then((response)=> {
  	return response.json();
  })
  .then((response)=> {
  	console.log(response);
  })
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });
</script>

Ví dụ 1':

<!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>JSON Test</title>
</head>
<body>
  <div id="myData">cccccc</div>
  <script type="text/javascript">
  fetch('https://jsonplaceholder.typicode.com/todos')
    .then((response) => {
      return response.json();
    })
    .then((response) => {
      appendData(response)
    })
    .catch(function(err) {
      console.log('Fetch Error :-S', err);
    });
  function appendData(data) {
    var mainContainer = document.getElementById("myData");
    for (var i = 0; i < data.length; i++) {
      var div = document.createElement("div");
      div.innerHTML = 'Name: ' + data[i].title;
      mainContainer.appendChild(div);
    }
  }
  </script>
</body>
</html>im

Ví dụ 2:

C:\xampp\htdocs\register\index.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>
	<script>
		var UserName = 'lionel3';
		var UserEmail = 'lionel3@gmail.com';
		var UserPassword = '123456';
		fetch('http://192.168.1.100/register/user_registration.php', {
		  method: 'POST',
		  headers: {
		    'Accept': 'application/json',
		    'Content-Type': 'application/json',
		  },
		  body: JSON.stringify({
		    name: UserName,
		    email: UserEmail,
		    password: UserPassword
		  })
		})
		.then(response => response.json())
		.then(responseJson => console.log(responseJson))
		.catch(error => console.error(error));
	</script>
</body>
</html>

C:\xampp\htdocs\register\user_registration.php

<?php
include 'DBConfig.php';
$con      = mysqli_connect($HostName, $HostUser, $HostPass, $DatabaseName);
$json     = file_get_contents('php://input');
$obj      = json_decode($json, true);
$name     = $obj['name'];
$email    = $obj['email'];
$password = $obj['password'];
$CheckSQL = "SELECT * FROM UserRegistrationTable WHERE email='$email'";
$check    = mysqli_fetch_array(mysqli_query($con, $CheckSQL));
if (isset($check)) {
  $EmailExistMSG  = 'Email Already Exist, Please Try Again !!!';
  $EmailExistJson = json_encode($EmailExistMSG);
  echo $EmailExistJson;
} else {
  $Sql_Query = "insert into UserRegistrationTable (name,email,password) values ('$name','$email','$password')";
  if (mysqli_query($con, $Sql_Query)) {
    $MSG = 'User Registered Successfully';
    $jsons = json_encode($MSG);
    echo $jsons;
  } else {
  	$MSG = 'Try Again';
    $jsons = json_encode($MSG);
    echo $jsons;
  }
}
mysqli_close($con);
?>
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 30, 2020 at 07:19 PM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.9

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `register`
--

-- --------------------------------------------------------

--
-- Table structure for table `userregistrationtable`
--

CREATE TABLE `userregistrationtable` (
  `id` int(255) UNSIGNED NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `userregistrationtable`
--

INSERT INTO `userregistrationtable` (`id`, `name`, `email`, `password`) VALUES
(10, 'Lionel', 'phamngoctuong1805@gmail.com', '123456'),
(15, 'lionel1', 'lionel1@gmail.com', '123456'),
(16, 'lionel2', 'lionel2@gmail.com', '123456'),
(17, 'lionel3', 'lionel3@gmail.com', '123456');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `userregistrationtable`
--
ALTER TABLE `userregistrationtable`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `userregistrationtable`
--
ALTER TABLE `userregistrationtable`
  MODIFY `id` int(255) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Get and Post method using Fetch API

Last Updated: 08-11-2019

The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object.

The basic syntax of a fetch() request is as follows:filter_none

brightness_4

fetch(url, {options}).then(data => { // Do some stuff here}).catch(err => { // Catch and display errors})

The difference between XMLHttpRequest and fetch is that fetch uses Promises which are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

However there are still some browsers that do not support fetch() method, so for those, we have to stick with the XMLHttpRequest object.

A fetch() method can be used with many type of reuqests such as POST, GET, PUT and DELETE.

GET method using fetch API: In this example, we are going to use JSONPlaceholder which provides REST API get and post random data such as posts, users, etc.

First of all, create an HTML file with the following code:filter_none

brightness_4

<!DOCTYPE html><html lang="en"> <head> <title>Fetch API</title> </head> <body> <div> <h1>Fetch API GET REQUEST</h1> <h3>Fetching Users</h3> <!-- Table to display fetched user data --> <table id="users"></table> </div> <!-- Link JavaScript file --> <script src="main.js"></script> </body></html>

In JavaScript, file contains the following codefilter_none

brightness_4

// main.js // GET request using fetch()fetch("https://jsonplaceholder.typicode.com/users") // Converting received data to JSON .then(response => response.json()) .then(json => { // Create a variable to store HTML let li = `<tr><th>Name</th><th>Email</th></tr>`; // Loop through each data and add a table row json.forEach(user => { li += `<tr> <td>${user.name} </td> <td>${user.email}</td> </tr>`; }); // Display result document.getElementById("users").innerHTML = li;});

You can get more data from the request, refer to the documentation.

POST request using fetch API: The post request is widely used to submit forms to the server. Fetch also supports the POST method call. To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we’ll do a POST request on the same JSONPlaceholder and add a post in the posts. It’ll then return the same post content with an ID.

In the same JavaScript file add the following content:filter_none

brightness_4

// main.js // POST request using fetch()fetch("https://jsonplaceholder.typicode.com/posts", { // Adding method type method: "POST", // Adding body or contents to send body: JSON.stringify({ title: "foo", body: "bar", userId: 1 }), // Adding headers to the request headers: { "Content-type": "application/json; charset=UTF-8" }}) // Converting to JSON.then(response => response.json()) // Displaying results to console.then(json => console.log(json));

Now if you open your javascript console and refresh the page you’ll see a result like below –

The API returns a status of 201 which is a HTTP status code for Created.

Last updated

Was this helpful?