Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php inside javascript function [closed]

What i am trying to do is inside script tags run javascript inside the php loops. For example:

<script>
$('#mydiv').mouseover(function(){
time();
function time(){
<?php  
    $secs = 45; 
    $secs--;
if($secs <= 25){
?>//javascript code here 
}
});
</script>

My main purpose is when the user mouseover a div, a javascript function runs and inside that javascript function there is php if conitions. If the time is less then 25 then do a specified javascript code. then another condition if the time is less that 10 then do another javascript function.Any type of help will be appreciated. THanks

like image 775
Jasminder Pal Singh Avatar asked Jun 18 '26 22:06

Jasminder Pal Singh


2 Answers

JavaScript is client-side script, PHP is server-side script. So, either you do AJAX calls to server or just pure JS.

AJAX+PHP:

<script>
    $('#mydiv').mouseover(function(){
        $.ajax({
            url: 'secs.php',
            success: function(data) {
                var secs = parseInt(data);

                if(secs <= 10) {
                    // do stuff
                }
                else if(secs <= 25) {
                    // do stuff
                }
            },
        });
    });
</script>

secs.php:

<?php
    session_start();

    if(!isset($_SESSION['secs'])) $_SESSION['secs'] = 45;
    else echo $_SESSION['secs'] --;
?>

Pure JS:

<script>
    var secs = 45;

    $('#mydiv').mouseover(function(){
        secs --;

        if(secs <= 10) {
            // do stuff
        }
        else if (secs <= 25) {
            // do stuff
        }
    });
</script>
like image 187
Jānis Avatar answered Jun 21 '26 11:06

Jānis


PHP runs on the server and outputs some text.

The browser then interprets that text as HTML/JS/etc.

You can't run PHP in response to a client side event unless you issue a new HTTP request.

If you know the values that your PHP cares about at the time of page build, then you can generate JavaScript with that data stored in a variable.

like image 25
Quentin Avatar answered Jun 21 '26 11:06

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!