5

Why does this not work? This is the first thing in the body:

<?php
    if(isset($_POST['submit'])){
        echo "<script>$('.classToShow').show();</script>";
    }else{
        echo "<script>$('.classToShow').show();</script>";
    }
?>

classToShow is a simple div in the body. It won't show up and its not depending on the boolean condition, it must be the code...

While this works:

<?php
    if(isset($_POST['submit'])){
        echo "<script>alert('works');</script>";
    }else{
        echo "<script>alert('works');</script>";
    }
?>

So the simple JavaScript works, but the jQuery doesn't... Why is this?

4
  • 1
    What are the errors in the Javascript console? Commented May 27, 2015 at 10:59
  • 1
    Try it like echo "<script>$(document).ready(function() { $('.classToShow').show(); });</script>"; Commented May 27, 2015 at 10:59
  • Adon: Im new both to JavaScript and NetBeans, so i dont know where to look, NetBeans gives no error messages... Satpal: i give it a try Commented May 27, 2015 at 11:01
  • 1
    You can use Firebug (a firefox/Chrome extension) for javascript debugging. Some browsers (like firefox developers edition) has them built in. You need to debug your script and know what's happening before you post a problem. Commented May 27, 2015 at 11:03

2 Answers 2

5

This is your problem:

This is the first thing in the body

At that point the element with the class of classToShow does not exist yet, so nothing happens. You should wait for the DOM to be ready before you run that code.

On the other hand, if you just want to show something when a POST request was made, you can add it directly using php and you don't need jQuery to do that afterwards.

A common solution would be to show it directly using php and then use javascript to hide the message after a certain timeout.

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

4 Comments

True, if the need for this is as simple as it seems, you do not need to use javascript to hide it. You can simply use: <?php if(isset($_POST['submit'])){ echo "<input type='submit' value='submit' />"; } ?>
jep, your answer together with Satpal's comment is the solution! thx, i was suffering with this since a while...
if I may ask you, could you point out what did you mean by the php solution?
@user3435407 Something like echoing out a box directly: if (...) { echo '<div class="message-box>message submitted!</div>"'; }. And then you can use javascript to hide / remove that box after a certain amount of time. That also keeps your page clean as there is no need to output that box when a POST request was not made.
1

You can use $(document).ready() and inside that write the code

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.