Javascript Cheatsheet

Note to self: if you are looking at this, you're in for a bad time

Front-End

Ajax

Submit a POST request via a form without reloading the page

As an added bonus, this will also print the response output to the DOM.

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            // Create a compute node for the specified email and return its public IP address
            function createCompute() {
                // Handle the POST request and subsequent response data
                $.ajax({
                    type: "POST",
                    email: $("#email").val(),
                    url: "https://awesomeendpoint.com?email=" + $("#userEmail").val() + "",
                    crossDomain: true,
                    xhrFields: {
                        withCredentials: true
                    },
                    dataType: "text",
                    success: function (data, textStatus, xhr) {
                        if (textStatus === 'success') {
                            $("#responseDiv").html("<p>" +
                                data + "<br>");
                        }
                    },
                    error: function (data, textStatus, xhr) {
                        if (textStatus != 'success') {
                            $("#responseDiv").html("<p>" +
                                data.responseText + "<br>");
                        }
                    }
                });
            }
            // Submit the createCompute Form
            $("#createCompute").submit(function (event) {
                // Prevent the form from submitting via the browser's default action.
                event.preventDefault();
                createCompute();
            });
        });
    </script>
</head>
<body>
    <!-- The form to specify parameters for building an ec2 instance for a user-->
    <form id="createCompute">
        <input id="userEmail" type=hidden name="email" value="bob@gmail.com">
        <button type="submit" class="btn btn-default">Build compute node</button>
    </form>
    
    <!-- Output Div -->
    <div id="responseDiv">
    </div>
</body>
</html>

Resources:
https://stackoverflow.com/questions/298745/how-do-i-send-a-cross-domain-post-request-via-javascript - how to send a POST request with JQuery

https://stackoverflow.com/questions/18697034/how-to-pass-parameters-in-ajax-post#:~:text=post with one more parameter at the very end.&text=Try using GET method%2C,utf-8'%20%7D)%3B%20request. - how to send POST parameters in the URL instead of the request body

https://stackoverflow.com/questions/11503553/jquery-ajax-call-returns-non-json-data-but-i-get-a-syntaxerror - fix parseerror by setting dataType to "text"