skip to Main Content

I wrote two pieces of code to learn how jQuery and ajax work together. The first script would pass form data to the second script for further processing and then return data back to the calling script. The script was able to capture and pass email using isset(_POST["email"]. However it failed to capture submit event (isset(_POST["email"] would not capture submit).

I understand it is redundant trying to capture the submit event. Since only when submit button is clicked would the second script be called. Wondering if this is the reason jQuery/ajax does not support capturing submit event.

1st Script:

            <html>
            <head>
              <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
              <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            </head>
            <body>
            <form id="form" method="post">
                <span id="error" name="error"></span>
                <div><input type="text" id="email" name="email"></div>
                <div><input type="submit" id="submit" name="submit" value="submit"></div>
            </form>
            </body>
            </html>
            <script>
            $(document).ready(function(){
                $('#form').on('submit', function(event){
                    event.preventDefault();
                    $.ajax({
                        url:"test4.php",
                        method:"POST",
                        data:$(this).serialize(),
                        dataType:"json",
                        beforeSend:function()
                        {
                            $('#submit').attr('disabled','disabled');
                        },
                        success:function(data)
                        {
                            if(data.success) {
                                window.location = "http://localhost/index.php";
                            }
                            else
                            {
                                $('#submit').attr('disabled', false);
                                $('#error').text('error');
                            }
                        }
                    })
                });
            });
            </script>

2nd Script:

            <?php
            if(isset($_POST["submit"]))
            {
                    $data = array(
                    'success'  => true
                    );
            }
            echo json_encode($data);
            ?>

2

Answers


  1. Chosen as BEST ANSWER

    just found a lengthy discussion on this topic. Apparently the submit button has to be serialized manually for now.

    https://github.com/jquery/jquery/issues/2321


  2. Just change event to:

    $('#submit').click((event)=>{
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search