I want a submit type button to send a POST request.
I am thinking about something like this:
<form action = "" method = "post">
<button>Upvote</button>
<form>
where the string "Upvote" will be send as a name in the POST request.
I know this is not working, and I know there are ways using AJAX(javascript) but I am fairly new to this area. I am just wondering if this is possible in general.
Update
Someone suggest that using <input>
tag, I used it. The problem is it generate a GET rather than a POST.
This question is related to
html
You can do that with a little help of JS. In the example below, a POST request is being submitted on a button click using the fetch method:
const button = document.getElementById('post-btn');_x000D_
_x000D_
button.addEventListener('click', async _ => {_x000D_
try { _x000D_
const response = await fetch('yourUrl', {_x000D_
method: 'post',_x000D_
body: {_x000D_
// Your body_x000D_
}_x000D_
});_x000D_
console.log('Completed!', response);_x000D_
} catch(err) {_x000D_
console.error(`Error: ${err}`);_x000D_
}_x000D_
});
_x000D_
<button id="post-btn">I'm a button</button>
_x000D_
You can:
<input type="submit" ..>
, instead of that button.submit(..)
on it. Eg: form.submit()
. Attach this code to the button click event. This will serialise the form parameters and execute a GET or POST request as specified in the form's method attribute.You need to give the button a name and a value.
No control can be submitted without a name, and the content of a button element is the label, not the value.
<form action="" method="post">
<button name="foo" value="upvote">Upvote</button>
</form>
Source: Stackoverflow.com