blsn
blsn

Reputation: 1093

PHP code in JavaScript to get variable

When I press on any of the ‘region’ names in the list ('href' links), the matching list of 'cities' is showing underneath.

<?php while(has_list_regions()) { ?>
  <a href="javascript:show_region('<?php echo list_region_id() ?>');"></a>
<?php } ?>

<script type="text/javascript">
  function show_region(chosen_region_id) 
  {
      ;     
      $(this).slideDown(200);
      ;
        <?PHP $clicked_tag = 'chosen_region_id'; ?>
  }
</script>

Is it possible to include PHP code within a section of JavaScript? Because I need to get the ID of the selected ‘href’ that I clicked. I am trying to include the PHP code in the above JavaScript function but it doesn’t work.

Upvotes: 1

Views: 215

Answers (2)

techfoobar
techfoobar

Reputation: 66663

PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on.

You can however use PHP to generate the required JS along with your content.

The way you've written it won't work.


For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic)

function show_region(chosen_region_id) {
    ...
    $.post('yourserver.com/getclickedtag.php', 
        {clicked_tag: chosen_region_id}, 
        function(data) { ... });
    ...
}

Upvotes: 1

qooplmao
qooplmao

Reputation: 17759

In your script the variable chosen_region_id is already in the function so you don't really need to declare it again with PHP.

Upvotes: 0

Related Questions