Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a jQuery object from php?

Tags:

jquery

php

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?

like image 708
user3435407 Avatar asked May 27 '15 10:05

user3435407


1 Answers

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.

like image 126
jeroen Avatar answered Nov 14 '22 22:11

jeroen