Daniel Paczuski Bak Daniel Paczuski Bak - 1 year ago 82
PHP Question

HTML form: send data to javascript function

I have a html page. It has a number of forms.

I want a generic function that, after any form is submitted, will take all of the input of that form and send it as JSON to another server.

From what I understand, what I want is the following:

<form enctype="application/json" name="createStudentForm" onsubmit="sendForm()">
Student ID (must be 3 digit number):
<input type="text" name="student_id"><br>
Nickname:
<input type="text" name="student_nickname"><br>
<input type="submit">
</form>


And later:

<script>
function sendForm(){
console.log('sent form');
}
</script>


My question is: a) why does my console not log this when I submit? When I test using chrome, the console is empty after sending submit
and b), how can I access the form's inputs from inside sendForm()? Do I need to reference that form directly or is there a way to just pass the data to sendForm() when I call it?

Answer Source

Following up on what Michael said and using a little bit of jquery you can make this work very easily.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
  function sendForm(form){
    console.log('sent form: ' + $(form).serialize());
    return false;
  }
</script>
<body>
<form enctype="application/json" name="createStudentForm" onsubmit="return sendForm(this)">
    Student ID (must be 3 digit number):
    <input type="text" name="student_id"><br>
    Nickname:
    <input type="text" name="student_nickname"><br>
    <input type="submit">
</form>
</body>
</html>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download