0

Am trying to check a form submitted using jquery and php. Am making an .ajax request to the server to validate if data have been entered to the form and perform different operations depending on the callback response of the server. e.g show error message if firstname is not entered or lastname is not entered.

The problem is that when both are not entered the callback return's the message firstname and lastname together without revealing the error messages.

        // JavaScript Document
        $(function(){
            $("#form").submit(function(event){
                $("#name_alert").css("display,none");
                event.preventDefault();
                  $.ajax({
                      url:'functions/register_user.php',
                      type:"POST",
                      data:$(this).serialize(),
                      success:function(data){  
                           if(data=='true') 
                                {  
                                    $("#form").effect("shake", {times:2}, 600); 
                                    $("#alert").fadeIn("slow");
                                    $("#note").fadeIn("slow").html('<strong>ERROR</strong>: Your details were incorrect.');  
                                }
                            if(data=='name'){
                                    $("#name_alert").fadeIn("fast").effect("shake", {times:1}, 600);
                                    $("#name_note").html('<strong>ERROR</strong>: Your first name must be in the range
                                     of 2 to 20 characters long.'); 
                                }
                            if(data=='surname'){
                                    $("#surname_alert").fadeIn("fast").effect("shake", {times:1}, 600);
                                    $("#surname_note").html('<strong>ERROR</strong>: Your surname must be in the range
                                     of 2 to 20 characters long.'); 
                                }
                            else { 
                                    $("#name_alert").fadeOut("fast");
                                    $("#note").html('<strong>PERFECT</strong>: You may proceed. Good times.');  
                                    }  
                              }  
                        });
            });
        });

Server side code is checking if fields are empty or not from the form and echoing the corresponding messages like firstname or lastname. Afterwards jquery shows the right message depending on the output of the server.

7
  • 1
    Why don't you use Client side scripting for form validation? Commented Apr 16, 2013 at 11:46
  • You could just generate the error message server side and return to be shown on the client side after. @Shiju I see your point, but you should still check the submitted data server side. But yea checking client side first should save a couple of requests indeed. Commented Apr 16, 2013 at 11:49
  • i want to know the way with the server Commented Apr 16, 2013 at 11:49
  • I agree with @Shiju You should use client-side validation. But to answer on your current question you should provide us more information: what does your server return in response, when both name and surname are empty? Commented Apr 16, 2013 at 11:51
  • namesurname @MichaelSivolobov Commented Apr 16, 2013 at 11:52

2 Answers 2

2

Here is an example of how it could be done. I have tried to keep it simple:

Server side response example:

// If the posted value was left empty or not received return an error in json format.
If ( empty($_POST['value']) )
{
    echo json_encode(
         array('status' => false, 'error' => 'The value cannot be left empty'));
    return true;
}

Client Side ajax example:

$.ajax({
    url: "/url/to/your/script",
    type: "POST",
    data: 'your=data',
    dataType: "json",
    success: function(reply){
        // If the reply.status is false, show the error status message
        if( !reply.status ){
            alert( reply.error );
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You currently have error checking for the following cases:

  1. If the data returned is "true".
  2. If the data returned is "name".
  3. If the data returned is "surname" with an else statement which says the data is perfect.

The issues with these are: There is no checking for if BOTH surname and name are returned. Secondly, the else statement that returns whether the data is perfect or not is attached to the if (data == 'surname') which means that if it's not an issue with the surname, it will return that it is perfect.

if (data == 'true') {
    $("#form").effect("shake", {times:2}, 600); 
    $("#alert").fadeIn("slow");
    $("#note").fadeIn("slow").html('<strong>ERROR</strong>: Your details were incorrect.');  
} else if (data == 'name') {
    $("#name_alert").fadeIn("fast").effect("shake", {times:1}, 600);
    $("#name_note").html('<strong>ERROR</strong>: Your first name must be in the range of 2 to 20 characters long.'); 
} else if (data == 'surname') {
    $("#surname_alert").fadeIn("fast").effect("shake", {times:1}, 600);
    $("#surname_note").html('<strong>ERROR</strong>: Your surname must be in the range of 2 to 20 characters long.'); 
} else if (data == 'namesurname') {
    $("#name_alert").fadeIn("fast").effect("shake", {times:1}, 600);
    $("#name_note").html('<strong>ERROR</strong>: Your first name must be in the range of 2 to 20 characters long.');
    $("#surname_alert").fadeIn("fast").effect("shake", {times:1}, 600);
    $("#surname_note").html('<strong>ERROR</strong>: Your surname must be in the range of 2 to 20 characters long.');
} else { 
    $("#name_alert").fadeOut("fast");
    $("#note").html('<strong>PERFECT</strong>: You may proceed. Good times.');  
}

If you are checking exact values, it is best to use else if which will execute the next if statement only if the one before it is false. This will work it's way through the if statements and if they don't match exactly, it moves on to the next one. Based on your comment on the question, the return value if both name and surname are incorrect is "namesurname" which is the 4th if statement.

If the purpose of the if (data == 'true') is to test if there is data returned, you should change the layout to be something like this:

if (data.length < 0) {
    // If statements to check if data is 'name', 'surname' or 'namesurname'
} else {
    //Data is perfect.
}

This will check if the data that is returned has a length greater than 0 (is not an empty string) and will then check to match it to a value.

Another option would be to check it prior to form submission rather than wasting the time sending it to the server when you can tell it is wrong. This can be done with either the .length function (easy) or regex (not so much and for something like this, overkill).

e.g.

if ($('#firstnameInputField').val().length < 2 || $('#firstnameInputField').val().length > 20) {
    // first name is invalid since length is less than 2 or greater than 20
}

This can be put in an event or a function which you can call whenever you want to actually check the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.