Search code examples
phpjqueryajaxonclickonchange

Unable to trigger Ajax with onclick (but it triggered if using onchange)


I am new to Ajax here. I have a PHP file that has a form with simple elements in it. I want to be able to click "Submit" and then have the form data sent to another PHP file to process it (and this process may take long time), and then when it’s done, shall return some result (text, etc.) to the first PHP file. Here's my code:

<html>

<head>
    <script src="jquery.min.js"></script>
    <script>
        function submitBorrow() { // Call to the 'ajax' function

            $.ajax({
                type: "POST",
                url: "sendEmail.php",
                data: { test:'yes', wat:'no' },
                success: function(html)
                {
                    $("#emailResultDiv").html(html);
                }
            });
        }
    </script>

</head>

<body>
    <form id="borrowForm" name="borrowForm">
        <select name="duration" id="duration" onchange="submitBorrow();">
            <option value="3 days">3 days</option>
            <option value="4 days">4 days</option>
            <option value="5 days">5 days</option>
            <option value="6 days">6 days</option>
            <option value="1 week">7 days</option>
            <option value="2 week">14 days</option>
            <option value="3 week">21 days</option>
            <option value="1 month">30 days</option>
            <option value="40 days">40 days</option>
            <option value="60 days">60 days</option>
        </select>

        <button onclick="submitBorrow();">submitBorrow</button>

        <div id="emailResultDiv">Here</div>
    </form>
</body>

</html>

Here is content of my sendEmail.php (just a simple PHP code fragment with a fake process command sleep).

<?php
    if ($_POST) {

        sleep(5);
        echo "DONE!";
    }
?>

When I change the selected item, after 5 seconds, the value "DONE!" is displayed at the div. But when I press the button, it doesn't do that. Why is that, and how can I achieve what I need?


Solution

  • Rookie mistake. After posting a question, I just realized that all buttons in a form shall be Submitting the form if a type is not given.

    So I just did this, and it works:

    <button type="button" onclick="submitBorrow();">Borrow</button>
    

    I specified type="button" and it ceased to be a submit button and solved the issue I had.