Michael Paccione Michael Paccione - 4 months ago 16
Ajax Question

jQuery AJAX no error or success fired

I have a simple contact form then I am POST'ing out from. I am trying to AJAX the data with jQuery but for some reason I am not getting any response from the handlers. Is this code correct?



$(document).on("ready", function() {
$("#contactButton").on("click", function(e) {
e.preventDefault();

var data = {
clientName: $("input").eq(1).val(),
clientEmail: $('input').eq(2).val(),
clientMessage: $('textarea').val()
};

$.ajax({
type: 'POST',
url: 'email.php',
data: data,
dataType: 'json',
success: function(response) {
$("#contactButton").text("Thank You");
$("input").val("");
$("textarea").val("");
},
error: function(response) {
alert("Error: Message Not Sent");
}
});
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact">
<input type="text" name="clientName" placeholder="Name" required>
<input type="email" name="clientEmail" placeholder="Email" required>
<textarea name="clientMessage" required>Message</textarea>
<button id="contactButton">Contact</button>
</form>




Answer

The problem is because you haven't stopped the default form submission (just the button click), so the page is actually unloading before the AJAX completes. To fix this you should hook to the submit event of the form instead of the click of the button. Then you can stop the submission using preventDefault().

Also note that you can use the serialize() method on the form to get the entered data instead of building your own object. Try this:

$(document).on("ready", function() {
    $("#contact").on("submit", function(e) {
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: 'email.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response){
                $("#contactButton").text("Thank You");
                $("input").val("");
                $("textarea").val("");
            }, 
            error: function(response){
                alert("Error: Message Not Sent");
            }
        });
    });
});