0

I have the following code:

JS:

var flag = 0;
funct(){//makes changes on css
flag=0;}

HTML:

<form onsubmit="if(flag==1)return funct()">

PHP:

if(somethingIsOK){
    echo "<script>flag=1;</script>"; //should use new css which comes with funct()
}else{//do something else with keeping the existing css}

I want this structure, but I could not use the variable flag like I wanted to. I have tried making flag static but it did not work.

8
  • 2
    you cannot use the same variable both in JS and PHP Commented Jul 16, 2013 at 7:20
  • I assume the first part of the code is Javascript. Is this right? Commented Jul 16, 2013 at 7:20
  • Post your html + js on jsfiddle.net and update your question. Commented Jul 16, 2013 at 7:20
  • Dynamically change and check what variable? What condition? What is it you're trying to do? And post your (relevant/sscce) HTML here, not just at JS Fiddle. Commented Jul 16, 2013 at 7:21
  • I am sorry guys all are js, just if else parts are php, yes first part is js Commented Jul 16, 2013 at 7:22

5 Answers 5

1

Use the hidden field to set/unset flag

<input type="hidden" name="flag" id="flag" value="1" />

javascript

var flag = document.getElementById('flag').value;
funct(){//makes changes on css
document.getElementById('flag').value=0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can't easily use the same variable in both PHP and JS. What you can do however is make a <input type="hidden"> with the name flag and the value of the variable and then read it in both PHP and JS.

Comments

0

Its bad idea to use constructions like this, but if you realy want use some global variable you can assign it to window object property, i.e.:

window.flag = 0;

And use this variable(window.flag) everywhere you need it.

3 Comments

You are missing the point. The second part is in PHP while the first is in JS.
It doesn't matter, all js parts will be parsed after php.
Topicstarter doesn't used flag in php, he used it only in JS parts, no hidden field needed.
0

I don't like the way you do it, but the answer is to delete var before flag to make it global:

flag = 0;

proof

EDIT

  1. if you want to prevent form submit your funct() must return false;
  2. maybe you try

    if(somethingIsOK){
        echo "<script type="text/javascript">flag=1;</script>"; 
    }else{
        echo "<script type="text/javascript">flag=0;</script>"; 
    }
    

and again: it's a very-very bad idea to mix php and JS like that

Comments

0
var flag = 0;
funct(){//makes changes on css
flag=0;}

try

var flag = 0;
function funct(){  // <<<<< function
//makes changes on css
flag=0;}

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.