Reputation: 6252
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
Reputation: 639
$("#message").submit(function(event) {
event.preventDefault();
...
Upvotes: 2
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
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