Skip to content

Instantly share code, notes, and snippets.

@tranchausky
Created March 17, 2025 04:45
Show Gist options
  • Save tranchausky/c6aa8c60d6805b45be35571368189264 to your computer and use it in GitHub Desktop.
Save tranchausky/c6aa8c60d6805b45be35571368189264 to your computer and use it in GitHub Desktop.
javascript get post ajax example template
<?php
$data=[
'staus'=>true,
'msg'=>'welcome',
];
echo json_encode($data);
<!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>Test ajax get</p>
<div id="jsonContainer"></div> <!-- Where the JSON will be displayed -->
<p>Result get</p>
<textarea id="result_get" col="20" row="20" readonly>
</textarea>
<br>
<br>
<br>
<p>Result post</p>
<textarea id="result_post" col="20" row="20" readonly>
</textarea>
<script>
function getData(){
const params = new URLSearchParams({ id: 123, name: "John" }).toString();
fetch(`save.php?${params}`)
.then(response => response.json())
.then(data => showGetData(data))
.catch(error => console.error("Error:", error));
}
function showGetData(data){
document.getElementById('result_get').value= JSON.stringify(data);
}
function postData(){
fetch("save.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: 123, name: "John" })
})
.then(response => response.json())
.then(data => showPostData(data))
.catch(error => console.error("Error:", error));
}
function showPostData(data){
document.getElementById('result_post').value= JSON.stringify(data);
}
getData();
postData();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment