Reputation: 117
I'm doing it this way:
...submit(function() {
$.post(...,function() {
validate();
})
});
But it turns out that the form is submitted directly...
Upvotes: 0
Views: 4527
Reputation: 17319
you need to prevent the default form submission
http://api.jquery.com/event.preventDefault/
$("form").submit(function(event){
event.preventDefault();
if(valid())
{
$.post . . .
}
});
Upvotes: 0
Reputation: 207
If you want to AJAXily do server side validation without posting the form to another page, you could do something like this. Instead of binding the validation action to submit, you could instead make your "submit" button just a "button" type, and then bind your validation to it's click event. Once it passes validation, then you can move on.
For instance:
$('#myPseudoSubmitButton').click(function() {
// Send the form to the server side for validation
$.post('validation_script.php', { form inputs here }, function(data) {
if (data.validated) {
// Perform some functionality that happens when the form validates
}
else {
// Display an error message to the user
}
});
}, 'json');
This of course presupposes that your validation script returns JSON-formatted data with a "validated" attribute.
Upvotes: 0
Reputation: 318468
Have a look at the jQuery Validation Plugin.
Here's an example on how it could be used:
$("#myForm").validate({
rules: {
command: 'required'
},
messages: {
command: 'Please enter a command.'
},
submitHandler: function(form) {
$(form).ajaxSubmit({
success: function(data) { /* ... */ },
url: form.action,
dataType: 'json'
});
}
});
Upvotes: 4
Reputation: 57209
You'll have to grab each element and run it through your validation, then submit the form later.
Use $(id).value
(for id-d elements) or yourForm.someElementName.value
(for name-d elements, assuming your form is name
d yourForm
).
Upvotes: 0