post html form results to api as json

Tags: , , ,



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.

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>
    <script>
        $('#myForm').ajaxForm({
            url : 'myurl.com', 
            dataType : 'json',
            success : function (response) {
                alert("The server says: " + response);
            }
        });
    </script>
</head>

<body>
    <form class="myForm" method="POST" action="myurl.com">
        <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>

        <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>

        <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">
        </div>

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

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?

Answer

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.
  $.ajax({
    url: 'myurl.com',
    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.



Source: stackoverflow