Send Data From NodeJS Back To Same Html Page After Form Submission
Solution 1:
You can't send data to an HTML page. HTML is a static file format and cannot receive data by itself. A server can, but not an HTML file.
What you can do however, is intercept your post request on the client side, send it to the client using XHR and receiving back the data on the client side again, then do whatever you want when the script receives datos
. Basically everything happens between the JavaScript part of the page and the Node server that receives POST data and sends back datos
.
Here's a simple example of how you can intercept the POST request on the client side:
document.querySelector('form').onsubmit = evt => {
// don't submit the form via the default HTTP redirect
evt.preventDefault();
// get the form values
const formData = {
name1: document.querySelector('input[name=name1]').value,
name2: document.querySelector('input[name=name2]').value
}
console.log('formData:', formData);
// send the form encoded in JSON to your server
fetch('https://your-domain.com/path/to/api', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(formData),
})
// receive datos from the server
.then(resp => resp.json())
.then(datos => {/* do what you want here */})
// catch potential errors
.catch(err => console.log('an error happened: '+err));
}
<form>
<input name="name1" value="value1">
<input name="name2" value="value2">
<button type="submit">Submit</button>
</form>
PS: The above snippet will fail with a network error because only the client-side script is present - there is nothing running at https://your-domain.com/path/to/api
, but you already included the right server code in your question. Just end the server script by res.send(datos)
.
Post a Comment for "Send Data From NodeJS Back To Same Html Page After Form Submission"