Submit form data to call a web service (Javascript)

If you want to create a small web project, a approach would be to use a combination of bootstrap (frontend), lumen (backend) and jquery (interaction between the two). It is a very strong combination with a very low owning and maintenance cost that can easily scale (by upgrading to laravel) if needed. You can also use angular with does not add a lot of overhead.

While you are trying to implement the above, the following pattern is encountered a lot of times: you need to call a web service via js while the data are filled by the user via a form on the html page. While the web service is being called, you need to show a spinner on the page so that the user understands that he needs to wait until the call has been completed.

Step 1: Style the spinner however you like (there are a lot of examples available) and set default visibility to hidden:

css
.spinner {
    ...
}
.hidden {
    display:none;
}

Step 2: Place the spinner and set an ID for the form (eg: myID):

html
...
<form id="myID" ... >
    .... 
    <input type="submit" ... > 
</form> 
...

Then use submit event of the form:

js
$("#myID").on('submit', function (e) {
    e.preventDefault();
    $("#spinner").toggleClass("hidden");

    $.ajax({
        type: 'POST',
        url: '',   // URL of the web service
        data: $(this).serialize(),
        success: function (data) {
            $("#spinner").toggleClass("hidden");

            // do sth on data
        }
    });
});

 

 

References for ajax via javascript:

https://gist.github.com/sirleech/5047400

https://stackoverflow.com/questions/21450629/how-to-call-a-webservice-method-from-an-html-page-javascript-with-out-refresh

References for spinners:

https://codepen.io/MattIn4D/pen/LiKFC

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s