Jump to content

js var from php var SOLVED with thanks


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 post
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 post
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 post
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 post
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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...