0

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" class="requires-validation">
    <div class="d-flex flex-row align-items-center mb-4">  
        <i class="fas fa-key fa-lg me-3 fa-fw"></i>
        <div class="d-flex form-floating mb-0 flex-fill">    
            <input name="yourname" type="text" class="form-control name" placeholder="Type your name" >
            <label for="yourname" class="form-label">Your Name</label>
            <div class="yournameerror">Name field is valid!</div>
        </div>
    </div>    

    <div class="d-flex flex-row align-items-center mb-4">  
        <i class="fas fa-key fa-lg me-3 fa-fw"></i>
        <div class="d-flex form-floating mb-0 flex-fill">   
            <input name="email"  type="email" class="form-control" placeholder="Type a valid email" >
            <label for="email" class="form-label">Your Email</label>
            <div class="emailerror">Name field is valid!</div>
        </div>    
    </div>

    <div class="d-flex justify-content-center mx-4 mb-3 mb-lg-4">
        <button type="submit" class="btn btn-primary btn-lg" 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.

3
  • 1
    if($errors !== '') will always be true, because $errors is an array. Use !empty instead. Commented Jul 19, 2022 at 12:25
  • 1
    Try var_dump($_POST); to see what the PHP fie is getting from the ajax. However, you're just sending the empty new FormData(); with an action, you never append or grab the values from the form. Commented Jul 19, 2022 at 12:28
  • @aynber do you mean like this ? prnt.sc/BcQUF2ePdCSt - not getting anything in the console. I removed values grabbing section first to check the response in ajax and validation Commented Jul 19, 2022 at 12:51

1 Answer 1

1

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'));
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I updated like that and here is my method now prnt.sc/9EOBIxmLuKsn but I still see the same issue.
@FoolishCoder Sounds as if $_POST['yourname'] == '' and empty($_POST['email']) are true. What is the output of var_dump($_POST); exit();? Maybe var data = new FormData(); in your JavaScript part clears the POST data.🤔 I think it should be var data = new FormData(document.getElementById('profile-update'));.
thank you so much. after adding var data = new FormData(document.getElementById('profile-update')); like this prnt.sc/YBDGQqUnPZvP I see the message <div class='alert alert-success'>Article added</div> in the console like this prnt.sc/uxVS7unpG2ux but before that I see this alert alert("Not Uploaded"); but the other lines X marked in this screenshot prnt.sc/6zCSkCGaOOtl returns nothing. so if the validation passes I see success message and the alert but not other console prints from else condition in the Ajax
@FoolishCoder Oh, sorry, I didn't see the typing error in the PHP code at $reponse['success'] = true;". There is missing an "s": $response['success'] = true;". I fixed it also in my answer above and added a notice for the FormData change.

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.