html form post json example
- Published
- Reading time
- 2 min read
- Length
- 307 words
On this page
HTML Form Post JSON Example#
If you are looking for an HTML form post JSON example, you have come to the right place. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.
Using HTML Form and JavaScript#
One way to post JSON data from an HTML form is to use JavaScript. Here is an example:
function submitForm() {
var data = {
name: document.getElementById('name').value,
email: document.getElementById('email').value
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/api/users', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify(data));
}
In this example, we have a form with two inputs, one for name and one for email. When the form is submitted, JavaScript creates a JSON object with the values of the inputs, sets the content type header to "application/json", and sends the JSON object to the server using a POST request.
Using HTML Form and PHP#
Another way to post JSON data from an HTML form is to use PHP. Here is an example:
$data = array(
'name' => $_POST['name'],
'email' => $_POST['email']
);
$options = array(
'http' => array(
'header' => 'Content-type: application/json',
'method' => 'POST',
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents('http://example.com/api/users', false, $context);
In this example, we have a form with two inputs, one for name and one for email. When the form is submitted, PHP creates a JSON object with the values of the inputs, sets the content type header to "application/json", and sends the JSON object to the server using a POST request.
These are just two examples of how to post JSON data from an HTML form. There are many other ways to do it, depending on your needs and the tools you have available.