AJAX: Using the Fetch API: (non IE compatible)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Fetch GET</title>
</head>
<body>
<h1>Welcome</h1>
<script>
fetch("simple.php").then(res => res.json()).then(data => {
console.log(data.message);
});
</script>
</body>
</html>
simple.php
<?php
$data = [
"message" => "Hello, World!"
];
echo json_encode($data);
- Open terminal (from the folder you placed those two files) and run
php -S localhost:8080
- In your browser head to
localhost:8080
(you should see "Welcome")
- Open Dev tools (hit F12)
- In the Console you should see
"Hello, World!"
To make it apparent that no page refresh is happening, you could create a button, an on click go fetch the data:
<h1 id="title">Welcome</h1>
<button id="btn" type="button">Get title</button>
<script>
const EL_title = document.querySelector("#title");
const EL_btn = document.querySelector("#btn");
EL_btn.addEventListener("click", () => {
fetch("simple.php").then( res => res.json()).then(data => {
EL_title.textContent = data.message;
});
});
</script>
https://i9i.xyz/3qoih
- why don't you rather show a minimal reproducible example of what you have so far?