2

Okay, so the idea is that I need a piece of javascript to run once an if statement in php has been met however this needs interaction with the dom, so assume a button being pressed and a variable has been passed to the php on button press. (It isn't that senario but fairly similar):

if ($button == 1){
    echo '<script type="text/javascript"> document.getElementById("myForm").submit(); </script>';
}

And I want once this condition is met for this code to run. It needs to be within the php if statement I can't move it to js. However I did think about trying to add the code into a variable and passing that variable to the js via ajax but didn't work.

Any help would be much appreciated.

3
  • 4
    That doesn't make sense. PHP runs on the server. You need AJAX polling or WebSockets. Commented Apr 7, 2013 at 15:54
  • Is'nt it kind of an oxymoron to have a PHP condition relying on the DOM (not counting ajax etc) ?? Commented Apr 7, 2013 at 16:03
  • Why don't you just use JavaScript to see if the button has been pressed? Commented Apr 7, 2013 at 16:29

1 Answer 1

1

do you mean just wanting to run a piece of javascript, after a php condition is met? If so:

myScript.php

<?php
    $button = 1;
    if ($button == 1){
      echo "submit form";
    }
?>

myScript.js

$.ajax({
  type:"POST"
  url:"myScript.php"
  success: function(data){
    if(data == "submit form"){
      //submits "myForm"
      $("#myForm").submit();
    }
  }
});

as said by SLaks, its not possible to execute javascript in php, because php runs on the server, and javascript runs on the client. to make it easier to understand: they are basically 2 seperate "worlds" which can only run certain code.

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

3 Comments

Yeah, that makes sense, however with your code I am getting a error message of "missing function declaration" and "unexpected identifier".
hmm, gimme a sec and ill test it out on my server. by the way, what i posted isn't enough code to work by itself
nah, he means putting the ajax call in a function. but he hasn't specified what calls the function, so ill just take a random guess hah

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.