Jump to content

js var from php var SOLVED with thanks


niche

Recommended Posts

In this external learning script (saved as a .js), why does the string of the php code display instead of the value of the url variable?

<?php$url = "http://localhost";?> var url = "<?php echo $url; ?>"; alert(url);

Edited by niche
Link to comment
Share on other sites

(saved as a .js)
well, there's your first problem. ;) you would have to do something like this
<?php $url =  'http://localhost'; echo '<script type="text/javascript">';echo 'var newUrl = ' . $url;echo 'alert(newUrl)';echo '</script>'; ?>

Edited by thescientist
  • Like 1
Link to comment
Share on other sites

Thanks big dave and thescientist. If that's as bad as the ridicule gets, I know I'm getting off easy. I work with very few external javascripts consequently I just couldn't see it. This just reminds me that I still haven't broken that habit I have of seeing what I expect to see. Six eyes were obviously better than two. EDIT Assuming we're all human (have to practice being alert to that seeing what I expect to see thing). lol.

Edited by niche
Link to comment
Share on other sites

Even if you give a file a .php extension you can still load it as a Javascript file using the <script> tag. Just to ensure it's interpretted correctly you can send a javascript mime type header. <?phpheader('Content-type: text/javascript');?> In the HTML file:<script src="file.php"></script>

  • Like 1
Link to comment
Share on other sites

Wow. Didn't know that. So, in the situation I'm working with, I would substitute <script type="text/javascript" src="file.php"></script> for <script type="text/javascript" src="subcat.js"></script> in the head of my index.php and run the javascript in subcat.js out of file.php. Is that what you're saying?

Edited by niche
Link to comment
Share on other sites

Building on post #6 How would the file.php look? I know this isn't right, but how should it read?

<?phpheader('Content-type: text/javascript');$url = "http://localhost";echo '<script type="text/javascript">';  var url = "<?php echo $url; ?>";  alert(url);echo '</script>';?>

Link to comment
Share on other sites

php within javascript within php is brand new to me as of today. Who would've thunk?

<?php$url = "http://localhost";header('Content-type: text/javascript');echo 'var url = "' . $url . '";';echo 'alert(url);';?>

Thanks ingolme

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...