I am using PHP Zend framework and jQuery ajax to submit and validate a form using json data format. The PHP works great, the ajax works great too. The only problem is that if the form has more than one invalid input (e.g name and email are both invalid), the ajax executes error:function() part.
Here is the ajax code:
.ajax({
type:'POST',
url:'processForm.php',
dataType:'json',
data:str,
success:function(data){
//do something when ajax call is complete
//setup variables
switch (data.internal_code){
case 0:
$('#NameError').html(data.msg0);
break;
case 1:
$('#EmailError').html(data.msg1);
break;
case 2:
$('#TextError').html(data.msg2);
break;
case 3:
$('#contactForm').fadeOut(2000);
$('#successMessage').fadeIn(2000);
$('#successMessage').fadeOut(4000);
break;
}
},
error:function(data){
alert ("ajax did not work");
}
Please let me know how I can fix this error.
you need to look at what is in the error
callback and determine what's going on. Or alternatively, open up webkit inspector or firebug and look at what is coming back from the server.
If your request works for valid input or input with 1 error, and you get the error callback for 2 invalid inputs, I bet the server is crashing and returning a 500. Without looking at the response from your server, its impossible to help more.
You cannot use a switch statement to check multiple forms because the outcome is only one set of actions.
The normal way to do it is to explicitly encode your JSON on the server to give a more meaningful result:
if(data.internal_code_0){
// do something
error++;
};
if(data.internal_code_1){
// do something else
error++;
};
// then at the end of the field processing
if(error == 0) {
// reset form field states and button states
// no need to submit form again - it has already been done!
};
You see here I am using explicit data.internal_code_0
it actually doesn't matter what value it contains, rather that it is either set or not, and therefore I can deal with multiple errors on the client side using ìf
s.
Also I count the number of errors so that at the end of processing I know if all the fields have passed muster or not.
On the PHP side do this
if(!isset($_POST['inputFieldHTMLName']))
{
// do something
}
else
{
$errors['internal_code_0'] = 'you forgot to enter a value ';
};
// ... check other fields
if (count($errors, 1)>0)
{
echo json_encode($errors);
}
else
{
// form is good. Continue with processing
};