Send Post data to the server with JavaScript

let’s say i have one table

--
-- Database: `demo`
--

-- -------------------------------------------------------
CREATE TABLE IF NOT EXISTS `members` (
  `member_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`member_id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`user_id`,`name`) VALUES
(1,'Admin');

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

here is php code to insert data

<?php
error_reporting(~E_NOTICE);
if(isset($_POST['add'])){
    $name=strip_tags($_POST['name']);
$sth=$db->prepare("INSERT INTO members(name)VALUES(?)");
$sth->bindparam(1,$name,PDO::PARAM_STR);
$sth->execute();
   }
?>

and html form to handle user input

<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no">
<title>demo</title>
</head>
<body>
<form method="post" name="myForm">
<input type="text" name="name" placeholder="Enter name">
<button type="submit" name="add">Submit</button>
 </form>
</body>
</html>

how can I achieve the same thing by using javascript? I heard about xhttpRequest and formData objects, but I don’t know exactly how to use them to make things good

Answer

Here’s a quick JavaScript example using the FormData & Fetch APIs.

const myForm = document.getElementById('myForm'); // Grab the form;

//Handle the submit listener;
myForm.onsubmit =e=>{
  e.preventDefault(); // Disable default form actions.
  let formData = new FormData(); // Initiate a new FormData Object
  let name = e.target.name.value; // Grab the "name" input value from the form.
  formData.append('name',name); // Append the varible to the FormData object.
  
  
  fetch('http://localhost/testpost.php',{
    'method':'POST', // Use POST method for this fetch request.
    'body':formData // Set the formData as the fetch request's body.
  })
    .then(res=>res.text())
    .then(data=>console.log(data));
  
  
}