Sherwin Flight
Sherwin Flight

Reputation: 2363

Calling validation through ajax function

I have two pieces of javascript that I would like to work together. I have a form that is submitted via ajax, and a form validation script, that I would like to work together to prevent the ajax form submission if the validation fails.

Here is the ajax form submission script:

<script type="text/javascript">
$(document).ready(function(){$(".sendName").click(function(){
var jsuser=$("#jsuser").val();
var jemail=$("#jemail").val();
var jusid=$("#jusid").val();
$.post("recomend.php",{jsuser:jsuser,jusid:jusid,jemail:jemail},function(data){$("#loadName")
.html(data)
.effect('bounce', { times: 5, distance: 30 }, 300);
  });
 });
});
$('#start').click(function() {
  $('#effect').toggle('fast', function() {
   });
});
</script>

This code works perfectly, and the form is submitted.

I also have the validation code partially working. If incorrect information is entered the error message is shown beside the field, but the form can still be submitted.

On a normal form the validation code is called like this:

<form method="post" action="formprocess.php" name="form1" id="form1" onsubmit="return validate(this)">

So, I need to know how to do the equivalent of:

onsubmit="return validate(this)"

in the ajax submission code, and not submit the form if there are errors.

Upvotes: 0

Views: 496

Answers (2)

Phrogz
Phrogz

Reputation: 303251

$(".sendName").click(function(){
  if (!validate(this.form)) return;
  // rest of your function, including AJAX call
});

The .form property is available on all form elements (HTMLSelectElement, HTMLOptionElement, HTMLInputElement, HTMLTextAreaElement, HTMLButtonElement, HTMLLabelElement, HTMLFieldSetElement, HTMLLegendElement, HTMLObjectElement, and HTMLIsIndexElement).

Upvotes: 1

stevebot
stevebot

Reputation: 24005

Why don't you just do the following?

<script type="text/javascript">

$(document).ready(function(){$(".sendName").click(function(){

var jsuser=$("#jsuser").val();
var jemail=$("#jemail").val();
var jusid=$("#jusid").val();
if(validate(jsuser, jemail, jusid)){
$.post("recomend.php",{jsuser:jsuser,jusid:jusid,jemail:jemail},function(data){$("#loadName")
.html(data)
.effect('bounce', { times: 5, distance: 30 }, 300);
  });
 });
});
$('#start').click(function() {
  $('#effect').toggle('fast', function() {
   });
});
}
</script>

Where validate does your validation

Upvotes: 1

Related Questions