1

I want to do the validation on my PHP side and then have my JQuery code display your changes have been saved when the submit button is clicked but the JQuery code states that the changes have been saved even when the validation fails.

How can i fix this so that PHP can do the validation and then JQuery can do its thing when PHP has finished its validation?

Here is my Jquery code.

$(function() {
    $('#changes-saved').hide();
    $('.save-button').click(function() {
        $.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(html) {
            $('div.contact-info-form').html(html);
            $('#changes-saved').hide();
            $('#changes-saved').html('Your changes have been saved!').fadeIn(4000).show();
        });

        $('a').click(function () {
            $('#changes-saved').empty();
            $('#changes-saved').hide();
        });

        return false; // prevent normal submit
    });
});

Here is part of my PHP code.

// Check for an email address:
if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) {
    $email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email']));
} else {
    echo '<p class="error">Please enter a valid email address!</p>';
}
0

2 Answers 2

2

in the jquery you can add a if statment that check if the php validation pass, in the php you need to return a value like 1\0 or true \ false.

and check this parameter in jquery

i add example its using json but is the same issue

jquery :

        $.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(data_pack){
            if(data_pack.msg ==1){
                # success do something ....
                            .........
            }

            alert(data_pack.html);

        }, 'json');

the php code like :

if($validation_ok){
   $arr = array('msg'=>1,'html'=>$html);
}
else {
   $arr = array('msg'=>0,'html'=>$error_msg);
}
echo json_encode($arr);
exit;
Sign up to request clarification or add additional context in comments.

1 Comment

How would my JQuery if statement look like. Kind of new to JQuery.
1

You should validate it with both client-side and server-side (ie. with both JavaScript and PHP). If this is not possible, I'd consider posting the form asynchronously and parsing the reply from the server with javascript to determine whether the changes were saved.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.