0

How can I make my error messages appear after validation in PHP using AJAX

Hi, I'm currently working on my ajax and I'm tryng to figure out on how will my error message appear on my form. I've already tried to echo the error but what I want is show the error on every invalid field.

here's my html code:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <style>
        span{
            display: none;
        }
    </style>
</head>
<body>
    <form action="test2.php" method="POST" id="formLogin" class="pass">
        name: <input type="text" name="name" id="name">
        <span id="name">Invalid!</span> 
        <br>
        description: <textarea name="description" id="description"></textarea>
        <span id="desc">Invalid!</span>
        <br>
        image file: <input type="file" name="image" id="image">
        <button type="submit"  ></button>
    </form><br>
    <p class="form-message"></p>
    <script src="ajax.js"></script>
</body>

heres my ajax code:

$(document).ready(function(){
            $("#formLogin").submit(function(event){
            event.preventDefault();
            $.ajax({
                url: 'test2.php',
                type: 'POST',
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,
                success: function(data)
                {
                    if(data.name == "1"){
                        $("span#name").css("display","block");
                    }else{
                        $("span#name").css("display","none");
                    }
                    if(data.desc == "1"){
                        $("span#desc").css("display","block");
                    }else{
                        $("span#desc").css("display","none");
                    }
                }
            });

        });
    });

and my php code;

<?php
    $myObj = new stdClass();


    if(empty($_POST['name'])){
        $myObj->name = "1";
    }

    if(empty($_POST['description'])){
        $myObj->description = "1";
    }

    $myJSON = json_encode($myObj);

    echo $myJSON;
?>
1
  • this works for me. thanks you so much! Commented Mar 18, 2018 at 2:06

1 Answer 1

1

In success of ajax, you receive the data in json formate , before use the data.name you have to reqiure parse json like
data=$.parseJSON(data) OR data=JSON.parseJSON(data)
then use data.name

Sign up to request clarification or add additional context in comments.

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.