简体   繁体   中英

calling php variable in external.js file

I am trying to access a PHP variable from an external file.js, then use the variable to control output of a function in the file.js .

i tried using input hidden field to hold the variable , and in the file.js , use $("#id").val() to retrieve the text value of the input, but it still does not work.

myfile.php i have this

<html>
<head>
    <script type="javascript" src="file.js"></script>
</head>
<body>
    <input type="hidden" id="myPhpValue" value="<?php echo $phpValue ?>">

and in file.js i have this

$(script);

function script(){
    //some codes 
    displayUser();
}

function displayUser(){ 
    var user = $("#myPhpValue").val();
    alert ("the user is "+user);
}

If user is Mike, i expect the output to show "the user is mike", but nothing shows

The possible reason that your code isn't working are:

  1. You haven't embedded jQuery library and been using $() identifier
  2. Your PHP variable $phpValue is empty

The following code works:

 var user = $("#myPhpValue").val(); alert ("the user is "+user);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <input type="hidden" id="myPhpValue" value="mike">

In your html move the script tag where your body's tag is closed. if it didn't work again then change your js code and write on this way

var element = document.querySelector("#myPhpValue").value; alert(element);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM