Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Shon Levi
6,036 PointsCan't understand AJAX checking
Hey you all, just finished Ajax Course and have a question...
If I want to make form in Ajax, in the vidoes he just explain how to make the submition but he didn't explain how to check the form...
This is how far I got:
$("#form").submit(function(evt) {
evt.preventDefault();
var url = $(this).attr("action");
$.ajax(url, {
method : "POST",
data : $("#add_task").serialize(),
success : function(response){
?????
}
});
});
I need to check for example if the email the user is enter is valid... how can I do that?!
Thanks all
BTW - How I make a code section in the forum here I can't do nothing but make tabs for make this up?!
1 Answer
jack AM
2,618 PointsHey Shon,
There are a bunch of ways to do what you want, here is a way that is pretty straight forward...
$("#form").submit(function(evt) {
evt.preventDefault();
if (!checkFormFields()) {
//show your error message to user...
alert('All fields required.');
} else {
var url = $(this).attr("action");
$.ajax(url, {
method : "POST",
data : $("#add_task").serialize(),
success : function(response){
}
});
}
});
//your form checking here...
function checkFormFields() {
return $("#username").val() !== '';
}
So basically all I did was wrap your ajax call inside the if else statement, if the form doesn't pass the validation test, then the ajax call doesn't happen.