Reputation: 5714
Apologies for opening what might be a basic question for more experienced users but Im learning Ajax it is a steep learning curve but I am slowly getting there. I have the following script which works perfectly, except for the client-side validation part. Im trying to stop the form from being submitted if form field is empty. However my validation part is not working (it gets ignored / skipped)
I would greatly appreciate it if someone with a bit of Ajax experience could give my code a scan and possibly advise where I am going wrong.
<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>
Upvotes: 3
Views: 3839
Reputation: 2588
I feel like my solution is a little simpler than the other answer provided.
If you have jQuery validation library installed (i.e.: jQuery.unobtrusive) it is as simple as:
$("form").on('submit', function(e) {
e.preventDefault();
if ($(this).isValid()) {
$(this).submit();
}
});
Otherwise I would just turn the submit button in to a regular button:
<button>Submit</button> instead of <input type='submit' />
And then do this:
$("button").on("click", function() {
if ($("form input[type=text]").val() == "") {
alert("Error!");
} else {
$.ajax({
url: "/my/forms/action",
type: "POST",
data: $("form").serialize(),
success: function() { }
});
}
});
Upvotes: 1
Reputation: 388316
You need to call the validation code inside your submit event handler, in your code you are running the validation in the dom ready handler then if the input field has contents then you are adding the event handler.
$(function () {
var form = $('#dep-form');
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();
//do the validation here
if (!validateDep()) {
return;
}
// 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;
}
})
Upvotes: 1