Try   HackMD

jQuery AJAX template

tags: javascript

html

<form id="form">
    <!-- inputs -->
    <button type="submit" id="submit">
        submit
    </button>
</form>

javascript

<script>
    $('#submit').click(function(e){
        e.preventDefault();
        var form = new FormData(document.getElementById('form'))
        $.ajax({ 
            url: "/api/endpoint",
            data: form,
            type: 'post',
            processData: false, // important
            contentType: false, // important
            cache: false,
            success: function(data)
            {
                console.log(data)
                // redirect
                window.location.replace(data.redirect);
            },
            error: function(data)
            {
                // integrate Swal to display error
                Swal.close();
                if (data.status == 419) {
                    window.location.reload();
                } else {
                    Swal.fire({
                        icon: 'info',
                        title: 'Error',
                        html: data.responseJSON.message,
                    });
                }
            }
        });
    })
</script>

backend

laravel server side response example

return response()->json([
    'message' => 'message ...',
    'redirect' => 'https://example.com/path'
], 200);