Skip to content

post html form results to api as json

I want to submit a form and have the values sent to the api in json format and save the response in a variable. When i try this using the below code i get an ‘Internal Server Error’ message.

    <script src=""></script>
    <script src=""></script>
            url : '', 
            dataType : 'json',
            success : function (response) {
                alert("The server says: " + response);

    <form class="myForm" method="POST" action="">
        <div class="form-group row">
            <label for="example-text-input" class="col-2 col-form-label">Season</label>
            <input class="form-control" type="text" id="season">

        <div class="form-group row">
            <label for="example-number-input" class="col-2 col-form-label">Students</label>
            <input class="form-control" type="number" id="num_students">

        <div class="form-group row">
            <label for="example-number-input" class="col-2 col-form-label">teachers</label>
            <input class="form-control" type="number" value="42" id="num_teachers">

        <button type="submit" class="btn btn-primary">Submit</button>

The parameters the api takes are ‘season’, ‘num_teachers’, ‘num_students’. Once it has all the parameters it will send a result response back. How can i send my form results to the api and get back the response?



I don’t know why you using a jQuery plugin to send form in Ajax, totally useless.

$('#myForm').on('submit', function() { // Fired listener when submit button is clicked.
    url: '',
    dataType : 'json', // Try text also, maybe the api donn't send result in json. Text always work.
    data: $('#myForm').serialize(); // The form to send.
    success : function (response) {// Get response on successful sever connection.
      console.log(response); // or alert
    }, error: function (err) { // Get error on failed connection to server.
      console.log(err); // or alert

Replace your function by that one. Remove action attribute on your html form tag. Now you handle errors and response from server. That means if the server returns an error, it will be displayed in your console and you will be able to know the problem. Other thing, do you really need this old version of jQuery, cause now we are at version 3.3.1.

User contributions licensed under: CC BY-SA
8 People found this is helpful