0

I'm trying to run the following code:

        if($thisIsSaved > 0 && $_SESSION["loggedIn"] == 1)
            {
                //show unsave
                echo "<script>$('#unsave').show();$('#save').hide();</script>";
            }
        elseif($thisIsSaved == 0 && $_SESSION["loggedIn"] == 1)
            {
                //show save
                echo "<script>$('#save').show();$('#unsave').hide();</script>";
            }
        else
            {
                echo "<script>$('#unsave').hide();$('#save').hide();</script>";
            }

<button id="save">Save</button>
<button id="unsave">Unsave</button>

I used to have this in pure PHP, no jQuery. What it did was, depending on the value of $thisIsSaved, it would display or not display either or both of the buttons. Now it's jQuery, and the page doesn't hold your save-state with jQuery as it can with PHP, so I have to find an alternate way of displaying and hiding the buttons in the beginning. Any help?

2 Answers 2

6

You need to wrap the contents within the script within a document.ready call:

...
echo "<script>$(document).ready(function() { $('#unsave').hide();$('#save').hide(); });</script>"; 
...

The problem is, since the execution of those scripts isn't deferred with document.ready, the jQuery commands are being run before the elements are actually parsed (since the buttons appear after the script tag).

It's usually best to make sure any jQuery that runs that touches the DOM be run within a document.ready to make sure everything has been parsed. You'll see this in most online examples.

All that being said, why offload the processing to the client? If you can output a class/style in PHP to hide/show the buttons, I'd recommend keeping that unless there is other specific client-side logic that needs to happen.

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

1 Comment

I agree. Since the state check is happening with data stored in PHP variables, why move the logic from PHP to jQuery/client side where a user could manipulate the html and do something you may not want.
0

Try putting the button html before the php that generates the jquery, so that when the page is rendered the buttons are defined before you try to hide/show them.

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.