babayaga
babayaga

Reputation: 31

php variable pass to java script and alert it

index.php

<?php
$loginmessage = "this is message";
?>

    $(document).ready(function(){
        $("#sb-btn").click(function() {
          alert("<?=$loginmessage?>");
          return false;
        });

    });

i have a button i wanted to when the button is clicked , it alert the $loginmessage by java script , but when i clicked it noting happen and no error as well. what i have to do to make the php variable pass to javascript and alert it when user clicked.

Upvotes: 2

Views: 89

Answers (4)

Regolith
Regolith

Reputation: 2971

Create a function that is called when a button is clicked. Pass the message that you want to alert to that function. Hope this helps. Checkout the code in snippet.

function alertSomething(test){
  alert(test);
}
<button name="samplebtn" onclick="alertSomething('test alert')">Test Alert</button>

Upvotes: 0

Rob
Rob

Reputation: 127

Try to write in console. Maybe your browser blocks alert messages. And-> are you see JavaScript errors in your console?

<script>
    $(document).ready(function(){
        $("#sb-btn").on("click", function() {
        var getvalue = '<?php echo $loginmessage; ?>';
        console.log(getvalue);
      });
     });

</script>

Upvotes: 0

ChristianF
ChristianF

Reputation: 2061

Depending upon your PHP version and host, the short tags could be disabled. They recently came back into use with PHP7, which is still in Release Candidate state.
What this means is that you might have to replace the short tags with the full <?php echo use. Look in the generated HTML code on the client, to find out if this is the case.

One small thing I'd like to nitpick on, is your terminology. :P
You're not actually passing a variable to JavaScript from PHP, as much as you're using PHP to generate parts of said JS. It might seem trivial, but the difference is a crucial one. Passing the variable implies something being handled in the same program, which isn't the case at all here. The PHP code gets executed on the server side, which generates plain text output to the client. The client (web browsers) in turn parses said content, and figures out what kind of content the different part of this text actually is.

Having this clear mental separation in mind when developing web applications/sites will make it a lot easier for you to understand the details of how things work, and in turn make it easier for you to come up with clean and simple solutions that works as intended. :)

Upvotes: 0

shubham715
shubham715

Reputation: 3302

Don't forget to call jquery library. then try this-

<?php
$loginmessage = "this is message";
?>

    <script>
        $(document).ready(function(){
            $("#sb-btn").on("click", function() {
            var getvalue = '<?php echo $loginmessage; ?>';
            alert(getvalue);
          });
         });

    </script>

Upvotes: 3

Related Questions