Trying to set Javascript Variable

Hi All,

I have a javascript that uses the following:

<script type=“text/javascript”>
var crcodes = {
Rcvbls: “1138”,
Rfds: “1138”,
Ntx: “4104”,
Txlb: “4104”,
Txmtls: “4104”,
SC: “4105”,
BD: “1138”

My script works now, but I want to set the right side of the variable (ie 1138) to be a variable that I retrieve from MySql and set up as a PHP variable.

That is, something like this: Rcvbls: “<?PHP $cash_cr ?>”

But no combination of anything I try works. The real problem here is that I know almost nothing about Javascript, so please, any help you can provide would be appreciated.



The way you currently have your PHP statement won’t output anything because its a variable, to retrieve the value you need to echo the variable like the example below.

var crcodes = {
    Rcvbls : <?php echo $cash_cr; ?>

Thanks, but that was one of the combination I tried, and when I do that, the script just stops the whole display of the HTML page.

Is there a link you can post as it would help to see whats going on by looking at the actual page.

Thanks for looking at this.

Here is the HTML page I am working with:

JD’s Makit Green

Is the link to the page you gave currently using the PHP statement?

No - That link is the link with the page that works. Here is a link with the php code in it that causes the script to stop:

JD’s Makit Green

Again, Thanks for looking at this.

Hi SgtLegend,

Clearly the problem is that the variable is not getting set properly. It probably has to do something with the fact that PHP code is server side and Javascript is client side. But I do not know how to overcome that and get the variable set properly.

The page is failing to load because the variable $cash_cr doesn’t exist in the global scope, what you can do while you work out why the variable isn’t been set is to use the below.

var crcodes = {
    Rcvbls : <?php echo isset($cash_cr) ? $cash_cr : 0; ?>

Still not sure how to get the variables to be in the “Global Scope”. I’ve tried lots of things, again with no luck. Can someone help me understand how to get the PHP Variables to be recognized within the Javasctipt routine.

Thanks again for your consideration to this issue.


Wow - Looks like I figured it out. Sometimes you just can’t see the forest for the trees. The solution was to simply create an include in the initialization portion of my page to include a PHP file that makes the MySQL call to the global variables file and set the variables before the Javascript executes.

Thanks to SgtLegend for his assist in identifying this solution.