简体   繁体   中英

Make PHP and JAVASCRIPT work together.

I have a simple php if statement that checks for an error return on a form submit basically.

<?php if ($this->session->flashdata('error')): ?>
    <a href="#" class="close" data-dismiss="alert">&times;</a>
    <div class="alert alert-error" id="error"><?php echo $this->session->flashdata('error'); ?></div>
<?php endif ?>

And I have this script that I want to put into this php so when the php is true the login box or account-container will shake.

$("#account-container").addClass("animated shake");

I tried echoing the script inside the php but all that was give me echo ; displayed on the page when the if was true.

Maybe you can use this script, I'm not at ease with jquery and you would have to adapt the code:

$(function(){
    if ($("#error").length !== 0) {
         $("#account-container").addClass("animated shake");
    }
});

Place it in the header as javascript source or embedded in a script tag

The $().load hook the containing handler to the onload event in the page* The function simply check if there is an element in the page with id error and add the class to the #account-container element if is the case.

  • I won't use $().ready() as the dom can still be partially rendered

References:

http://api.jquery.com/ready/ Says to use .load() function for onload event and alert that a <body onload="something"> tag is not compatible with the jquery event management

http://api.jquery.com/load/ Can be useful

I think that you are using Jquery for the javascript shake, you should call the javascript routine when the page is ready to load

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>shake demo</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
  <style>
  #toggle {
    width: 100px;
    height: 100px;
    background: #ccc;
  }
  </style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>

<p>Click anywhere to shake the box.</p>
<div id="toggle">This is rendered by PHP</div>

<script>
$( document ).ready(function() {
  $( "#toggle" ).effect( "shake" );
});
</script>

</body>
</html>

Note that the whole page is rendered by PHP, and the script will work when the document render is ready.

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