0

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 couldn't pass PHP variable to a Jquery file. Is really possible to do so?

function.php:

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

app.js : How can use this variable in app.js file below?

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

flwbtn.click(function(){
    var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();
    
    $.post("../php/flw.php",{flwusernameselected:selectflwusername})
    
});
});
4
  • just print it in the script no?.. Commented Nov 17, 2019 at 17:53
  • Sorry sir i did not understand! Can you explain pls? Commented Nov 17, 2019 at 17:54
  • post the script please Commented Nov 17, 2019 at 17:55
  • 1
    also, in JS you ca use the var keyword to create variables that can be get by all the functions (if declared outside blocks or other context), so you can use <script> var myvarible = <?php echo $variable = $fetch['username']; ?> <script> inside your document head, or at the beginning of the body, and than the other scripts should be able to access it Commented Nov 17, 2019 at 17:57

1 Answer 1

2

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()})

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

3 Comments

But I'm using the php in another page!
you can add some hidden element with id or clas and load it with js?
I did'nt get it sir!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.