简体   繁体   中英

Is there a better way to do this than echo?

I'm working PHP guest book which has some form validation (such as field highlighting when there is an error) that I only know how to do with JavaScript.

I have a simple form that looks like this:

<form action="$_SERVER['SELF']" enctype="multipart/form-data" method="post">
    <label for="guest_name">Guest Name:</label>
    <input id="post-name" class="noerror" type="text" name="guest_name">
    <input type="submit" name="submit" value="Let 'er rip" />
</form>

Which I am validating with the following function:

//Name Validation
if(strlen($_POST["guest_name"]) != 0){
    global $Name;
    $Name = $_POST["guest_name"];
} else {
echo '<script type="text/javascript">
        $(document).ready(function(){
            $("#post-name").removeClass("noerror").addClass("error");
        });
     </script>';
}

It works but I can't help but feel like this is a terribly inefficient way to go about this but my knowledge of PHP isn't quite there yet to figure out how to optimize this.

Don't rely on js

You can do that kind of thing without js any number of ways for example:

<form action="" enctype="multipart/form-data" method="post">
    <label for="guest_name">Guest Name:</label>
    <?php
    $class = 'noerror';
    if(empty($_POST["guest_name"])){
        $class = '';
    }
    ?>
    <input id="post-name" class="<?php echo $class ?>" type="text" name="guest_name">
    <input type="submit" name="submit" value="Let 'er rip" />
</form>

Note that double-negatives can get easily confusing (there is not no error) as such it's a better idea to always use positive logic checks:

<?php
$class = '';
if(empty($_POST["guest_name"])){
    $class = 'error';
}
?>
<input id="post-name" class="<?php echo $class ?>" type="text" name="guest_name">

Sticking to that principle usually leads to simpler and easier to understand code.

This is also possible

<?php
    if(strlen($_POST["guest_name"]) != 0) :
        $Name = $_POST["guest_name"];
    else :
?>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#post-name").removeClass("noerror").addClass("error");
        });
    </script>';
<?php endif; ?>

Don't send that huge script. Send a custom header with a simple error code. Your response handler can listen for headers (as distinct from the response text) and behave accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM