Home > OS >  PHP validation always returns error/false in ajax even the conditions are true
PHP validation always returns error/false in ajax even the conditions are true

Time:07-24

I have only two conditions. If the yourname is empty return error If the email is empty returns error but I get error even if both are not empty. I could not figure out why.

My Form

<form action="" method="post" name="contact-me" id="profile-update" >
    <div >  
        <i ></i>
        <div >    
            <input name="yourname" type="text"  placeholder="Type your name" >
            <label for="yourname" >Your Name</label>
            <div >Name field is valid!</div>
        </div>
    </div>    

    <div >  
        <i ></i>
        <div >   
            <input name="email"  type="email"  placeholder="Type a valid email" >
            <label for="email" >Your Email</label>
            <div >Name field is valid!</div>
        </div>    
    </div>

    <div >
        <button type="submit"  id="submit">Send message!</button>
    </div>
    <div id="nds_form_feedback"></div>
</form>

Validation function

<?php
function stack_update_validation_func(){
    $errors = array();
    $response = array();

    $yourname=$_POST['yourname'];
    $email=$_POST['email']; 

    if ($_POST['yourname'] == '')  {
        $errors['yourname'] = "Please enter your name"; 
    }

    if ((empty($_POST['email'])) ) {
        $errors['email'] = "Please enter your email";    
    } 

    $response['errors'] = $errors;

     if($errors !== '') {

        $response['success'] = false;
        $response['message'] = "Fail";

    } else {

        $reponse['success'] = true;
        $response['message'] = "<div class='alert alert-success'>Article added</div>";

         
    }
    header("Content-Type: application/json", true);
    echo json_encode($response);
    wp_die();
}

Getting that JSON response in this Ajax:

Please read the comments as well

<script type="text/javascript">
    jQuery(document).on('click', '#submit', function(e){
        e.preventDefault();
        var data = new FormData();

        data.append('action', 'stack_update_validation_func');   

        jQuery.ajax({
            type: 'POST',
            url: ajax_url,
            data: data,
            contentType: false, //because I have a file upload feild as well
            processData: false, //because I have a file upload feild as well
            headers: {Accept : "application/json;charset=utf-8"},
            dataType: 'json',
            debug:true,
            success: function(response) {
                if(response.success) {
                   jQuery("#nds_form_feedback").html('Sucessfully Sent'); // if the form passes the validation this works fine
                }
                else {
                    alert("Not Uploaded"); // shows the popup if there is a validation error

                    jQuery.each(response.errors, function(key, val) {   
                        console.log(key); // returns the key like this https://prnt.sc/I4R0rNdRIF0o
                    }); 

                    console.log(response); // returns the json response in console 
                    
                    jQuery.each(response.errors, function(key, val) {   
                        jQuery('#profile-update [name="' key '"]').parent().find('.' key 'error').html(val); 
                    });
                }
             }
       
    });
});
</script>

console.log(response); shows this

console output

but the issue is even yourname and email are filled correctly the error message is shown. not sure what is wrong. please help.

CodePudding user response:

In your method stack_update_validation_func there is a condition if($errors !== '') {. This condition will always be true because $errors will never be an empty string. It is initialized as empty array. So you should update the condition and your method could look like this:

function stack_update_validation_func()
{
    $errors = array();
    $response = array();

    $yourname = $_POST['yourname'];
    $email = $_POST['email']; 

    if ($_POST['yourname'] == '')  {
        $errors['yourname'] = "Please enter your name"; 
    }

    if (empty($_POST['email'])) {
        $errors['email'] = "Please enter your email";    
    }

    $response['errors'] = $errors;

    if(!empty($errors)) {

        $response['success'] = false;
        $response['message'] = "Fail";

    } else {

        $response['success'] = true;
        $response['message'] = "<div class='alert alert-success'>Article added</div>";

    }
    header("Content-Type: application/json", true);
    echo json_encode($response);
    wp_die();
}

Update: Here is also the part of the JavaScript, that had to be updated:

// instead of `var data = new FormData();`
var data = new FormData(document.getElementById('profile-update'));
  • Related