0

i have this source:

<div id="tst"></div>

<?php
function test($txt) {
    if ($txt == "aa") {
        return "true!";
    }
    return "false!";
}
?>

<script>
document.getElementById('tst').innerHTML = "<?php echo test('%s'); ?>".replace("%s","aa");
</script>

in this line : if ($txt == "aa") {

why the 'if' show me false? (meaning: aa != aa)

Something else I noticed, that if i use 0 instead of aa (in the JS and in the php source), and in the php source i use at "0" (with apostrophes), the 'if' show me "false" (meaning: 0 != 0). (EX.1)

but if i use at 0 (with no apostrophes) in the php source, the if show me "true" (meaning 0 == 0). (EX.2)

the ex.2, is the only that works fine!

Someone understand what the problem is? and how can i fix it?

EX.1:

<div id="tst"></div>

<?php
function test($txt) {
    if ($txt == "0") {     // with apostrophes
        return "true!";
    }
    return "false!";
}
?>

<script>
document.getElementById('tst').innerHTML = "<?php echo test('%s'); ?>".replace("%s","0");
</script>

EX.2:

<div id="tst"></div>

<?php
function test($txt) {
    if ($txt == 0) {     // with no apostrophes
        return "true!";
    }
    return "false!";
}
?>

<script>
document.getElementById('tst').innerHTML = "<?php echo test('%s'); ?>".replace("%s","0");
</script>

1 Answer 1

3

You're executing

<?php echo test('%s'); ?>

This is comparing '%s' == 'aa', which is false.

The reason Ex.2 returns true is because when you compare a string with a number, it converts the string to a number. A string that doesn't contain a valid number converts to 0, so '%s' == 0 is equivalent to 0 == 0, which is true.

You're calling replace in Javascipt but PHP runs on the server when the page is being created to send to the client, so it doesn't see Javascript changes (they happen in the future, how could they affect PHP?).

If you want to communicate from JS to PHP, you have to use AJAX.

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

1 Comment

you are wrong. in the begining the client change the souce, and after that its runs on the PHP server. the ex.2 works fine!

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.