0

I am trying to pass a variable through the onclick function into javascript.

So I am trying to pass

onclick = "purchase_song(<?php echo $row['filename']; ?> , <?php echo $row['price'] ?> )"

note the function works fine if I pass it a non php variable

onclick = "purchase_song( 'filename'  , 1)" 

And I use a similar technique to pass variables through hyperlinks and the GET function. Is it not possible to use PHP inside a javascript onlick? If so, what am I doing wrong.

Thanks,

3
  • 1
    PHP runs on the server. The HTML in the browser should look the same. Just view the page source in the browser and the difference between the static (non php) and the dynamic (php) version should be obvious. Commented May 17, 2014 at 22:39
  • Have a look at the generated code. It should be clear from that what the problem is. Also, Learn how to debug JavaScript. Commented May 17, 2014 at 22:50
  • Thanks, I had actually tried that but thought I had to put it in as &lsque; etc Commented May 17, 2014 at 22:53

2 Answers 2

3

If the values are valid strings then you are doing everything right except one thing : to pass php input as a string argument to the javascript function you should wrap it in single quotes ':

onclick = "purchase_song('<?php echo $row['filename']; ?>' , '<?php echo $row['price'] ?>')"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I had actually tried that but thought I had to put it in as &lsque; etc
0

The values should need to be quoted.

onclick="<?php printf("purchase_song('%s', '%s')", $row['filename'], $row['price'] ?>"

This example uses printf as its easer to see what the output from the format string.

Comments

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.