Last active
February 6, 2025 21:57
-
-
Save ismasan/bf9d539bdf817993b776bf3957ce2ef6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>JSON form</title> | |
<script> | |
function jsonForm(form) { | |
form.addEventListener('submit', function(event) { | |
event.preventDefault(); | |
var data = {}; | |
var inputs = form.querySelectorAll('input'); | |
for (var i = 0; i < inputs.length; i++) { | |
var input = inputs[i]; | |
data[input.name] = input.value; | |
} | |
fetch(form.action, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify(data) | |
}).then(function(response) { | |
return response.json(); | |
}).then(function(json) { | |
console.log(json); | |
}).catch(function(err) { | |
console.error(err); | |
}); | |
return false; | |
}); | |
} | |
document.addEventListener('DOMContentLoaded', function() { | |
var forms = document.querySelectorAll('[data-jsonform]'); | |
forms.forEach(jsonForm) | |
}); | |
</script> | |
</head> | |
<body> | |
<form data-jsonform action="/backend/first" method="post"> | |
<input type="text" name="name" id="name"> | |
<input type="text" name="age" id="age"> | |
<input type="submit" value="Submit"> | |
</form> | |
<form data-jsonform action="/backend/second" method="post"> | |
<input type="text" name="name" id="name"> | |
<input type="text" name="age" id="age"> | |
<input type="submit" value="Submit"> | |
</form> | |
</body> | |
<html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment