Jump to content

Passing php variable to JavaScript


tec-4

Recommended Posts

Hi everyone,

 

I'm curious if there is a way to reference a php variable in my js code (essentially replacing the "#sort_by", or at least the "/test.php" in the following code.  The code below works great for sorting currently using a select box but I am trying to utilize this same approach for a couple hundred pages and don't deem it practical to make one of these pieces of code per page.

 

Is there any way to reference a page specific variable that I can create per page, such as the URL (/test.php) that I can define and have my JavaScript utilize it?  I've tried a couple ways but seem very hacky.

 

 

$("#sort_by").change(function() {
      url = $("#url").val();
      window.location =  "/test.php" + url + $("#sort_by").val();
    });

 

Thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/246046-passing-php-variable-to-javascript/
Share on other sites

I dont know if youve already tried this but on my site I create global JS variables from PHP like this.

 

<script><?php getVariable() ?></script>

<?php
function getVariable() {
        // Some generated code to add to the variable
        echo "var jsVar = {$generated_php}";
}
?>

 

Might not be what you meant, hope it helps.

 

Well, really trying to somehow pass a page specific php variable to a javascript variable so that the "/test.php" in the following code can somehow be dynamic per page.

 

For example, I have a main JS file with:

 

$("#sort_by").change(function() {
      url = $("#url").val();
      window.location =  "/test.php" + url + $("#sort_by").val();
    });

 

and am trying to replace the "/test.php" with a url that is page specific to the page, like "/this-page.php" and was wondering if I could define a php variable like $variable = "/this-page.php" in my php file and somehow have my JS file reference this variable.

 

Have tried things like this:

 

$("#sort_by").change(function() {
      url = $("#url").val();
      window.location =  "<?php echo $variable; ?>" + url + $("#sort_by").val();
    });

 

but not having any luck...pretty new to JS so not really sure how make them function together.  But trying to have my .php page define a variable, call it from another page, and have my JS package it and make it function when I want to sort my page.  Does this make more sense?

 

Thanks!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.