Giovanni
Giovanni

Reputation: 838

Accessing a PHP variable from a JavaScript function in a webpage

Im sure this is possible, but I don't know JavaScript or PHP well enough to be able to figure it out myself!

I have an SQL database storing postcodes. I can retrieve that data from the database using PHP and get it showing in the webpage using:

<?php echo $row_getPosts['postcode']; ?>

However, I want to access this postcode in a JavaScript function in the head of the webpage. I've tried defining a var in the java and simply putting the code above into it, but that's mixing the PHP and the JavaScript languages together, an 'apples and pears' situation!!

Im presuming I must define a global variable i the html file, which both the PHP and JavaScript can interact with, but I don't know how to do this. Any help would be appreciated!

Upvotes: 0

Views: 103

Answers (4)

Alex Shilman
Alex Shilman

Reputation: 1547

You mean this:

<?php
$postcode= $row_getPosts['postcode'];
echo '
 <script type="text/javascript">    
  var postcode = "'.$postcode.'";
 </script>
';
?>

Upvotes: 1

pathfinder
pathfinder

Reputation: 1776

What you are echoing can be echoed inside a variable in the head of the same file or inside the function you are writing to the head:

<script>
var postcode = '<?php echo $row_getPosts['postcode']; ?>';
</script>

be sure this variable is put before the function runs in the head though.

or if the function is available, you could put it there too:

function blah() {
var postcode = '<?php echo $row_getPosts['postcode']; ?>';
rest of your code here
}

Upvotes: 1

user1864610
user1864610

Reputation:

There's no reason why you can't do this at some appropriate point in your code.

<?php
    $postcode = "SomePostCode";
    echo '<script> var postCode = "'.$postcode.'";</script>';
?>

This will create a global variable. You can just inject the variable into a function if it's more appropriate, in which case you won't need the <script> tags.

Upvotes: 1

NewInTheBusiness
NewInTheBusiness

Reputation: 1475

do like this:

var variable = <?php echo json_encode($row_getPosts['postcode']); ?>;

Upvotes: 2

Related Questions