user4016
user4016

Reputation: 11

jQuery $.post not performing validation properly

I am trying to have my form check for a valid birthdate by sending the data to a php file which checks for a valid birthdate, and then it echos the data for $.post to deal with.

Here is my JavaScript/jQuery:

$('#register_new_user').click(function(evt){
    evt.preventDefault();
    var error_array = new Array();
    var birthday_error_array = new Array();

    // confirm birthday is valid
        var day = $('#day').val();
        var month = $('#month').val();
        var year = $('#year').val();
        var birthday = day + "--" + month + "--" + year;
        $.post('data-test.php?function=birthday',{'birthday':birthday},function(data){
            alert(data);
            if(data != 'valid'){ birthday_error_array.push('error'); error_array.push('error'); }
        });

    // handle birthday validation information
    if(birthday_error_array.length >= 1) {
        $('#birthday_label').css("color","red");
        error_array.push('error');
    } else { $('#birthday_label').css("color","black"); }


    // check for errors if there are errors do not allow the form to be submitted
        if(error_array.length >= 1){
            return false;
        } else { return true; }
});

Here is my php page:

session_start();
require 'functions/db_functions.php';
require 'functions/functions.php';
if(isset($_GET['function']) && $_GET['function'] == 'birthday' && isset($_POST['birthday'])){
    $birthday = explode('--',$_POST['birthday']);
    if(!checkdate($birthday[1],$birthday[0],$birthday[2])){
        $result = 'invalid';                    
    } else {$result = 'valid';}
    echo $result;
}

I have confirmed that my php and the other page are communicating because I can alert out the return data of either valid or invalid within the $.post function. However, when I try to perform the if statement I have written above it does not work. It reads the valid information as invalid etc. I'm so confused.

Upvotes: 1

Views: 55

Answers (2)

user4016
user4016

Reputation: 11

I figured it out. I changed to a json for the communication between php and javascript, and I also used the .done() after the ajax function. It wasn't adding the value to the error array in time for the check to be run. The below code works properly:

JQuery:
var day = $('#day').val();
        var month = $('#month').val();
        var year = $('#year').val();
        var birthday = day + "--" + month + "--" + year;
        var birthdayArray = {"birthday": birthday};

        $.ajax({
          type:    "POST",
          dataType: "json",
          url:     'data-test.php?function=birthday',
          data:    birthdayArray,
          success: function(data) {
            if(data["result"] != 'valid') { 
                birthday_error_array.push('error');
                error_array.push('error');
            }
          }
        }).done(function(){
            if(birthday_error_array.length >= 1) {
                $('#birthday_label').css("color","red");
                error_array.push('error');
            } else { $('#birthday_label').css("color","black"); }
        });

PHP:
if(isset($_GET['function']) && $_GET['function'] == 'birthday' && isset($_POST['birthday'])){
    $birthdayArray = array();
    $birthday = explode('--',$_POST['birthday']);
    if(!checkdate($birthday[1],$birthday[0],$birthday[2])){
        $birthdayArray['result'] = "invalid";                   
    } else {$birthdayArray['result'] = "valid";}
    echo json_encode($birthdayArray); // return final result
}

Upvotes: 0

llernestal
llernestal

Reputation: 566

$.post() is asynchronous, meaning you supply a callback function that is invoked once the POST request is completed. if(birthday_error_array.length >= 1) is evaluated before the callback function is called

You need to check if(birthday_error_array.length >= 1) inside the callback function.

So something like this:

$('#register_new_user').click(function(evt){
    evt.preventDefault();
    var error_array = new Array();
    var birthday_error_array = new Array();

    // confirm birthday is valid
    var day = $('#day').val();
    var month = $('#month').val();
    var year = $('#year').val();
    var birthday = day + "--" + month + "--" + year;
    $.post('data-test.php?function=birthday',{'birthday':birthday},function(data){
        alert(data);
        if(data != 'valid'){ birthday_error_array.push('error'); error_array.push('error'); }

        // handle birthday validation information
        if(birthday_error_array.length >= 1) {
            $('#birthday_label').css("color","red");
            error_array.push('error');
        } else { $('#birthday_label').css("color","black"); }
    });
});

Upvotes: 1

Related Questions