對於開放可能是一個更有經驗的用戶的基本問題的道歉,但我學習Ajax是一個陡峭的學習曲線,但我慢慢到達那裏。除了客戶端驗證部分外,我有以下完美工作的腳本。 如果表單域爲空,我試圖停止提交表單。然而,我的驗證部分不工作(它被忽略/跳過)提交之前的Ajax驗證
如果有人有一點Ajax經驗可以給我的代碼掃描,並可能建議我哪裏出錯了,我將不勝感激。
<div id="depMsg"></div>
<form name="dep-form" action="deposit/submitReference.php" id="dep-form" method="post">
<span style="color:red">Submit Reference Nr:</span><br />
<input type="text" name="reference" value="" /><br />
<span id="reference-info"></span><br />
<input type="submit" value="Submit" name="deposit" class="buttono" />
</form>
</div>
$(function() {
var valid
//call validate function
valid = validateDep()
if(valid){
// Get the form.
var form = $('#dep-form');
// Get the messages div.
var formMessages = $('#depMsg');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
$(formMessages).html(messageHtml); // < html()
}
});
});
});
function validateDep() {
var valid = true;
if(!$("#reference").val()) {
$("#reference-info").html("(required)");
$("#reference").css('background-color','#FFFFDF');
valid = false;
}
return valid;
}
</script>