Hey you... FETCH ME THAT JSON!
We can jQuery AJAX or a straight up XMLHttpRequest. Now we can use the new Fetch API. Here is a short example on how to send data from an HTML form to PHP using the Fetch API. Let's have a play with it...
First we'll create a simple HTML form with 2 inputs and include scripts.js
which we'll create in the next step.
HTML (index.html)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FETCH JS</title>
</head>
<body>
<form id='form'>
<input type='text' placeholder='Name' name='name' required>
<input type='email' placeholder='Email' name='email' required>
<button type='submit'>Submit</button>
</form>
<script src="scripts.js"></script>
</body>
</html>
Now let's throw ourselves into the Javascript. Async ensures that the function returns a promise. Await waits for the promise to come through before returning its results. If there's an error we can catch it.
JS (scripts.js)
async function sendData(data, url) {
try {
const request = await fetch(url, {
method: 'POST',
body: data
});
const result = await request.json();
console.log(result);
} catch (error) {
console.error(error);
}
}
const form = document.getElementById('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
var data = new FormData(document.forms.form);
sendData(data, 'post.php');
});
Rolling onto the backend to pick up the form data sent from JS we'll check if the required fields are present and return some JSON with the results.
PHP (post.php)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$result = ['success' => false]; // MARK SUCCESS FALSE
if (isset($_POST['name']) && isset($_POST['email'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$result['name'] = $name;
$result['email'] = $email;
$result['success'] = true; // MARK SUCCESS TRUE
}
echo json_encode($result);
}
How do I send this data to an SQL database?
It's pretty simple stuff with PDO.
PHP (post.php)
function get_pdo()
{
$db_host = "localhost";
$db_name = "tutorial";
$db_username = "root";
$db_password = "root";
$dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
$options = [PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC];
$pdo = new PDO($dsn, $db_username, $db_password, $options);
return $pdo;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$result = ['success' => false]; // MARK SUCCESS FALSE
if (isset($_POST['name']) && isset($_POST['email'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$pdo = get_pdo();
$stmt = $pdo->prepare("INSERT INTO tutorial (name, email) VALUES (?, ?)");
$stmt->execute([$name, $email]);
$result['success'] = true; // MARK SUCCESS TRUE
}
echo json_encode($result);
}
And the SQL to create the table
CREATE TABLE tutorial (
ID int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
PRIMARY KEY (ID)
);
And a basic example on how to read from the database in PHP
$stmt = $pdo->prepare("SELECT * FROM tutorial");
$result = $stmt->execute([]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row["name"];
}
Thanks for reading. x