简体   繁体   中英

Unable to submit form on confirmation using JQuery

I am trying to submit a form using JQuery but it does not seem to be submitting. What am I doing wrong? This is my JS code: It does not log the hello word.

document.querySelector("form#myForm").addEventListener('submit', validateForm)
    function validateForm(e)
    {
        e.preventDefault();
        var values = $('#myForm').serialize();

         $.ajax({
            url: "<?php echo route('validate') ?>",
            method: 'GET',
            async:false,
            data: values,
            success: function(data) {
                var data = JSON.parse(data);
                var text = data.text;
                var image_url = data.image;
                swal({
                    html: "<div style='text-align: left; margin-left: 10px'><strong>Preview</strong></div>",
                    showCancelButton: true,
                    confirmButtonText: "Yes",
                    cancelButtonText: "No",
                    confirmButtonColor: "#00ff55",
                    cancelButtonColor: "#999999",
                    reverseButtons: true,
                }).then((result) => {
                    if (result.value) {
                        $("#myForm").submit(function(e){
                            console.log('hello')
                        });
                    }
                });
            }
    });
    return false;
}

This is the form opening tag attributes - <form action="{{url('test')}}" method="post" onsubmit="return validateForm(e);" id="myForm" name="a-form"> <form action="{{url('test')}}" method="post" onsubmit="return validateForm(e);" id="myForm" name="a-form">

Since you don't see your hello on your console (developer tools), did you also check for any errors. It's most likely not printed due to that.

As for your code, document.querySelector("form#myForm").addEventListener('submit', validateForm) is basically doing the same thing as onsubmit="return validateForm(e);". So it'd actually be doing the request twice. You can remove either one. Also do make sure your route is printed correctly on the url .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM