0

I don't know if this is possible as i know php is server side and javascript is client side.

But i am trying to run this javascript code from an if isset inside a php page.

I am using this code:

 <?php
    if( isset($_POST['submit2'])){
        echo "
            <script type=\"text/javascript\">
                $(document).ready(function(){
    setTimeout(function () {
        doWork();
        window.location.reload();
    }, 2000);

    function doWork() {
        $('#submit').trigger('click');
    }

});
</script>";
     }
  ?>

this javascript should click on the button named (submit) and it works fine if its not inside the PHP echo.. and I also checked to see if the if if( isset($_POST['submit2'])) actually returns a value and it does and it works as it should.

So, I don't know what the issue is here>

can some one please help me out with this?

7
  • Is this page is called via ajax? Commented Sep 11, 2013 at 13:37
  • @shadow, no. its a php page on its own. Commented Sep 11, 2013 at 13:39
  • not sure what you trying to do Commented Sep 11, 2013 at 13:39
  • @tonoslfx, I am trying to run that javascript if the value is sent from submit2. that's all. Commented Sep 11, 2013 at 13:40
  • 1
    @EnergyLynx EnergyLynx $(document).ready <- well you do use jquery. Did you have a look at the pages source inside your browser? Your browser should be able to tell you if there are any syntax errors in the output js (developer tools). Commented Sep 11, 2013 at 13:57

1 Answer 1

1

I have always found it best to keep my main javascript/jquery code within the head tag and use php to check and set variables that allow my scripts to run; echoing a javascript boolean into my JS block using php. This way you know that the javascript is doing what it should natively and not worry about elements not being treated properly in the DOM.

So I would do this (I don't know the order in which you want things to happen so this might seem out of order but the principle should still be the same):

<?php
if( isset($_POST['submit2'])){
    $varSet = "var set2 = 1;";
} else {
    $varSet = "var set2 = 0;";
}
?>


<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type=\"text/javascript\">
    $(document).ready(function(){

        <?php echo $varSet; ?>

        if(set2 == 1){
            setTimeout(function () {
                doWork();
                window.location.reload();
            }, 2000);

            function doWork() {
                $('#submit').trigger('click');
            }
        }
    });
</script>
</head>
Sign up to request clarification or add additional context in comments.

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.