Home » Php » javascript – How do i make my php variable accessible?

javascript – How do i make my php variable accessible?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to implement a timer. I learned this idea from a SO post.

<?php

  if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
  {
    //secondsDiff is declared here
    $remainingDay     = floor($secondsDiff/60/60/24);
  }
?>

This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function

                        //url:"onlinetest.php",
                        //dataType: 'json',
                        beforeSend: function()
                        {
                            $(".startMyTest").off('click');
                            setCountDown();
                        }

It will call setCountDown() method, which contains a line at the very beginning

     var days = <?php echo $remainingDay; ?>; 

When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is

Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.

How to&Answers:

The problem is, since initial load, $_POST values aren’t populated (empty on first load),

That variable you set is undefined, just make sure you initialize that variable fist.

<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
    //secondsDiff is declared here
    $remainingDay     = floor($secondsDiff/60/60/24);
    echo json_encode(array('remaining_day' => $remainingDay);
    exit;
}
?>

<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
    $.ajax({
        url: 'something.php',
        dataType: 'JSON',
        type: 'POST',
        beforeSend: function() {
            // whatever processes you need
        },
        success: function(response) {
            alert(response.remaining_day);
        }
    });
});
</script>

That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.

Answer:

You can pass a php variable into JS code like

var jsvariable ="<?php echo $phpvariable ?>";

NOTE:

If you ever wanted to pass a php’s json_encoded value to JS, you can do

var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here

Answer:

Try this,

var days = "<?php echo $remainingDay; ?>";