BendEg
BendEg

Reputation: 21088

Send single hidden field with form using javascript

Currently I'm working with ASP.Net and a nested form. My problem is, that ASP.Net only allows one form per page, but I need a kind of sub-form to redirect to another page.

My idea was to create a submit using JavaScript, but I don't get how to set the content of the post, which will be send.

For example I've tried to use the following code:

<div>
    <input type="hidden" value="ABCDE" />
    <input title="Send Form" onclick="this.form.method = 'post'; this.form.action = 'https://externpage/url'; this.form.submit();" type="submit" />
</div>

My problem is, that the content of the request should only be the hidden fields containing ABCDE and not all fields on the page. How can i achieve this using JavaScript and HTML?

Thanks a lot!

Upvotes: 1

Views: 386

Answers (1)

Jordan Davis
Jordan Davis

Reputation: 1520

Use FormData() to do the encoding.

sendForm=(e)=>{
    let data = new FormData();
    let hidden = document.querySelector('button').parentNode.firstChild.value;
    data.append('hidden',hidden);
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange=()=>(xhr.readyState == 4) ? console.log(xhr.response) : null;
    xhr.open('POST','http://yoururl.com');
    xhr.send(data);
}
document.addEventListener('DOMContentLoaded',()=>{
    document.querySelector('button').addEventListener('click',sendForm);
});

Upvotes: 2

Related Questions