简体   繁体   中英

JQuery not running from PHP echo

I am trying to execute some simple JQuery commands in an echo statement from PHP after the user submits a Log In form.

The user is able to Log In with the correct credentials, however if they enter incorrect ones it should show the invalid credentials paragraph.

Here is the code:

<?php
    //PHP code for login in, working, not needed to show
    echo 'Testing
        <script>
            $( ".wrong" ).show( "slow" );
        </script>';
?>


<!DOCTYPE html>
<html>

<head>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body class="login">

<form action="" method="post" class="login-form">
    <p class="wrong" style="display: none;">Invalid Credentials</p>
    <a class="link" href="#">Forgot your password?</a>

    <button type="submit" class="login-btn" name="submitLogin">Log in</button>
</form>

</body>

NOTE: The Testing value from the echo displays, yet the JQuery does not execute.

It is not possible to put the PHP code after the HTML as it creates a session for my login form to work.

<?php
    echo 'Testing
        <script>
            $( ".wrong" ).show( "slow" );
        </script>';
?>

This does not create a session, and does not need to be at the top. What needs to be at the top is a session_start() call yes, but echoing out script html is not required at the top

For instance you could do

<?php
session_start();
if(attemptLogin()){
  //logged in path
} else {
  //wrong credentials
  $LoginError = true;
}
?>

<!doctype html>
<html>
<head>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <?php if($LoginError):?>
    <script>
        jQuery(document).ready(function(){
            $( ".wrong" ).show( "slow" );
        });
    </script>;
    <?php endif;?>
</head>

You need to allow your js files to be loaded first, then the DOM to be loaded and then you can use your code below just before the </body> tag and it will work.

<?php
    //PHP code for login in, working, not needed to show
    echo 'Testing
        <script>
            $( ".wrong" ).show( "slow" );
        </script>';
?>

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