mister martin
mister martin

Reputation: 6252

Having trouble submitting a form with AJAX

HTML:

<form id="message">
  <input id="message-text" name="message" type="text" value="" autofocus="autofocus" />
  <input type="submit" value="Send" />
</form>

JAVASCRIPT:

$(document).ready(function () {
    // submit new message
    var request;
    $("#message").submit(function(event) {
        // abort any pending request
        if (request) {
            request.abort();
        }

        var $form = $(this);
        var $inputs = $form.find("input, select, button, textarea");
        var postData = $form.serialize();
        // note: we disable elements AFTER the form data has been serialized
        $inputs.prop("disabled", true);
        request = $.ajax({
            url: "submit.php",
            type: "POST",
            data: postData
        })
        .done(function(response, textStatus, jqXHR) {
            console.log('Success: ' + textStatus, jqXHR);
        })
        .fail(function(jqHXR, textStatus, errorThrown) {
            console.error('Error: ' + textStatus, errorThrown);
        });
    });
});

I've confirmed that submit.php works when not using AJAX to submit, so I don't think that's the problem. The console log simply says: Error: error on line 66: console.error('Error: ' + textStatus, errorThrown); which is completely non-descriptive nor helpful... The page also refreshes when I hit enter or click submit, which isn't supposed to happen.

Any ideas what I'm doing wrong?

Upvotes: 3

Views: 78

Answers (3)

Ideal Bakija
Ideal Bakija

Reputation: 639

 $("#message").submit(function(event) {
event.preventDefault();

...

Upvotes: 2

Paresh Gami
Paresh Gami

Reputation: 4782

I prepare demo for you please download it from

https://www.dropbox.com/s/24h0o9n08iuvpo1/ajaxdemo.rar

Change as per your requirement. I think it is helpful

Upvotes: -1

Mehran Hatami
Mehran Hatami

Reputation: 12961

This happens because you use submit input, this is the default behavior of submit input, so you have 2 options first is disable the submit using event.preventDeafult(); on the submit process, or you can easily change your send button:

<input type="submit" value="Send" />

to

<input type="button" value="Send" />

Upvotes: 3

Related Questions