0

I seem to be having an issue, I have a Javascript code,and it contains php variables

<?php   // Database information 
$name="whatever"; 

$mp3 = "Link/to/track/";
echo "
var myPlaylist = [{
    mp3:'mix/4.mp3',
    title:'$name',
}]]; </script>";

Upon trying to encode this,I'm able to encode the Javascript part, but it displays my variable names (in this instance $name) instead of the value(whatever)

4
  • It is of course inside a .php file, as .js files are not parsed by PHP as default (you can set it to parse them). Commented Feb 16, 2013 at 1:15
  • Try this: title:'" . $name . "' Commented Feb 16, 2013 at 1:15
  • 2
    Your PHP code is fine but I can't help but to notice that the Javascript isn't. Commented Feb 16, 2013 at 1:26
  • Your code is ugly but works fine on my computer , not sure what you are talking about when you say encode. Commented Feb 16, 2013 at 1:37

2 Answers 2

2

Whenever you're transferring information between PHP and JS like this, use json_encode. 1) You know that you're building a proper JavaScript structure (in your code, you're not...you're closing the array twice), and 2) you protect from escaping issues. Try:

<?php
$name = 'whatever';
$mp3 = '/link/to/track';

$json = array(array('mp3' => $mp3, 'title' => $name));
print "var myPlaylist = " . json_encode($json);
Sign up to request clarification or add additional context in comments.

Comments

0

That should work, but try this anyway

title:'".$name."',

or

title:'{$name}',

Since you used double quotes it should render php variables, single quotes wouldn't but you are not using those. Also make sure to escape the name because what if it had a single quote in it? It would break your javascript (unless its strictly controlled and you know for a fact it will not have a single quote in it).

3 Comments

Neither of them worked, it returned back :$name instead of the value
Are you sure php is running? Start a new page with just this code and see what happens. <?php echo time(); ?> Do you see a big number or the code when the page loads?
Php's running fine, as the same page, houses all my php connector information

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.