Skip to content
Advertisement

How to pass a PHP variable to an another .JS file for using it in JQUERY?

I’m a JQUERY begginner. I’m trying to pass a PHP variable to a js file so that i can use it in JQUERY! But found no resource to learn to do so. I’m able to pass a JQUERY variable to a different php file but I coundn’t pass PHP variable to a jquery file. Is really possible to do so?

function.php:

<?php $variable = $fetch['username']; ?>

how can use this variable in app.js?

$(document).ready(function(){ var flwbtn = $(“.findrowpplfollowbtn”);

flwbtn.click(function(){
    var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();
    
    $.post("../php/flw.php",{flwusernameselected:selectflwusername})
    
});
});

Advertisement

Answer

Echo it to HTML temaplate. If it’s some structure/array use for example json format.

<script>
<?php $variable = $fetch['username']; ?>
var js_variable = <?php echo json_encode($variable); ?>
</script>

or echo some hidden element like

<input type="hidden" id="custId" name="custId" value="<?php echo($fetch['username']); ?>">

and grab if with Jquery like

<script>
$( "#custId" ).value();
</script>

with your code JS:

$(document).ready(function(){ var flwbtn = $(".findrowpplfollowbtn");

flwbtn.click(function(){
    var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();

    $.post("../php/flw.php",{$( "#custId" ).value()})

});
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement