Friday, January 13, 2023

submitting a form without a refresh - jquery technique

This page - https://www.geeksforgeeks.org/how-to-submit-a-form-or-a-part-of-a-form-without-a-page-refresh-using-jquery/ - has a nice javascript form submitter code snippet. Another interesting thing there is that the form is submitted to https://reqres.in/api/users - which is a free API testing site. 

<script src=

"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">

    </script>

    <script type="text/javascript">

    $(document).ready(function() {

        $('form').on('submit', function(event) {

            event.preventDefault();

              

            // It returns a array of object 

            let userinfo = $(this).serializeArray();

            let user = {};

            userinfo.forEach((value) => {

                  

                // Dynamically create an object

                user[value.name] = value.value;

            });

            let url = "https://reqres.in/api/users";

            $.ajax({

                method: "POST",

                url: url,

                data: user

            }).done(function(msg) {

                  

                // When the request is successful

                $('span').text('user is successfully created with Id ' + msg.id);

            }).fail(function(err, textstatus, error) {

                $('span').text(textstatus);

            });

        });

    });

    </script>

If we're using this with Google Apps Script, we need to return 'Success' using something like 

return ContentService.createTextOutput().append('Success').setMimeType(ContentService.MimeType.JAVASCRIPT);

If there is no return statement, "error" is displayed in the form response SPAN.


No comments:

Post a Comment