Liondancer
Liondancer

Reputation: 16469

AJAX fires both success and error

I'm not sure why the error: portion of my ajax request is also firing. Both the success and error sections are firing actually. I'm pretty new to JS/jQuery but I read that success fires when the ajax request was successful and error fires when there is an error. I assume success means 200 and error means 400-500?

js:

    function create_post() {
        console.log("create post is working");
        var firstName = document.getElementById("firstname");
        var lastName = document.getElementById("lastname");
        var email = document.getElementById("email");
        var phoneNumber = document.getElementById("phonenumber");
        var message = document.getElementById("message");
        var contactInfo = {
            "first_name": firstName.value,
            "last_name": lastName.value,
            "email": email.value,
            "phone_number": phoneNumber.value,
            "message": message.value
        };

        $.ajax({
            url: "",
            type: "POST",
            data: contactInfo,
            success: ajaxSuccess(contactInfo),
            error: console.log("ajax fail")

        });
    };


    function ajaxSuccess(contactInfo) {
        console.log(contactInfo);
        // clear form data
        document.getElementById("contact-form").reset();
        // display modal
    }


//    Contact form submit
    var contactForm = document.getElementById("contact-form");
    $(contactForm).on('submit', function(event) {
        event.preventDefault();
        console.log("form submitted");
        create_post();
    });

enter image description here

Upvotes: 1

Views: 3668

Answers (2)

Alexander O'Mara
Alexander O'Mara

Reputation: 60527

Your problem is on these lines:

success: ajaxSuccess(contactInfo),
error: console.log("ajax fail")

This effectively running both functions immediately, and sets the return values of these functions to the success and error properties. Try using an anonymous callback function.

success: function() {
    ajaxSuccess(contactInfo);
},
error: function() {
    console.log("ajax fail");
}

Upvotes: 8

Quentin
Quentin

Reputation: 943564

You are calling functions and passing their return values to success and error. You need to pass actual functions.

Since, in both cases, you are hard coding the arguments to the functions, you can use bind to create the new functions.

success: ajaxSuccess.bind(window, contactInfo),
error: console.log.bind(console, "ajax fail")

Upvotes: 5

Related Questions