Tyler Brittin Tyler Brittin - 1 year ago 102
HTML Question

index.html:507 Uncaught TypeError: Cannot set property 'onsubmit' of undefined(…)

I tried searching but i cannot find anything that helps answer my questions. Im trying to send form data into JSON format. While also doing a console.log to see how the JSON is output and will be set to the server.

Below is my code. Thanks for any help!

<form enctype='application/json' style="text-align: center" method="post" name="form">
<input name="firstname" value="" type="text" class="form-control" placeholder="First Name"> &nbsp
<input name="lastname" value="" type="text" class="form-control" placeholder="Last Name"> &nbsp
<input name="email" value="" type="text" class="form-control" placeholder="Email"> &nbsp
<select name="category" value="" class="form-control">
<option selected disabled value="choose">--Category--</option>
<option value="furniture">Furniture</option>
<option value="books">Books</option>
<option value="music">Music</option>
</select> &nbsp
<input name="itemName" value="" type="text" class="form-control" placeholder="Item Name"> &nbsp
<input name="itemDesc" value="" type="text" class="form-control" placeholder="Item Description"> &nbsp
<input name="priceInput" value="" type="text" class="form-control" placeholder="Price ($00.00)"> &nbsp

<div class="modal-footer">
<button name="submit" value="" onclick ="onsubmit()" class="btn btn-default">Submit</button>

var form;

form.onsubmit = function (e) {
//stop regular form submission

//collect the form data
var data = {};
for (var i = 0, ii = form.length; i <ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;

//construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');

//send the collected data as JSON


xhr.onloadend = function () {


Answer Source

In your code:

var form;
form <-- currently is undefined
form.onsubmit === undefined.onsubmit

You can use the onsubmit function on elements in your DOM. In order to do that you need to set the form variable to reference the <form> element in your code.

You can use

var form = document.forms['form']

The usage of 'form' here is because your <form> tag has name="form".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download