user2185501
user2185501

Reputation: 5

PHP Variable in Echoing JavaScript

I have an php script that is echoing JavaScript, in the JavaScript there are PHP variables

echo '<script type="text/javascript"> 
     FB.init({
    appId: "myid",
    channelUrl: "//mysite/channel.html",
    status: true, // check login status
    cookie: true, // enable cookies to allow the server to access the session
    xfbml: true // parse XFBML
});
FB.getLoginStatus(function (response) {
    if (response.status === "connected") {
        FB.api("me/bookvote:download", "post", {
            book: "<?php echo "http://mysite/auction_details.php?name=$item_details["name"]&auction_id=$item_details["auction_id"]";?>",
            fb:explicitly_shared = "true" //? Is syntactically valid but creates a global
        }, //Missing a , here?

However, I am still getting:

Uncaught SyntaxError: Unexpected identifier for book: http://mysite.xom/auction_details.php?name=$item_details["name"]&auction_id=$item_details["auction_id"]";?>",

What should I do?

Upvotes: 0

Views: 127

Answers (4)

Steve Tauber
Steve Tauber

Reputation: 10159

You'll want to end your echo quote so it's like this:

echo '<script type="text/javascript"> 
....
            book: "http://mysite/auction_details.php?name=' . $item_details["name"] . '&auction_id=' . $item_details["auction_id"] . '",
....

Upvotes: 0

Paul Calabro
Paul Calabro

Reputation: 1906

Those variables never got converted to their actual values that are supposed to be used. Try breaking that string into multiple parts via concatenation.

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

I can spot multiple issues:

  • You try to print variables inside of single quotes. They won't be parsed, you need double quotes, or better yet, HEREDOC, or even better yet, don't use echo to print HTML/JavaScript.
  • You try to use additional <?php ?> tags inside of your echo. That would obviously not work.

Try this. I have removed the echo. Note that the larger PHP tag ends there.

?>
<script type="text/javascript"> 
     FB.init({
    appId: "myid",
    channelUrl: "//mysite/channel.html",
    status: true, // check login status
    cookie: true, // enable cookies to allow the server to access the session
    xfbml: true // parse XFBML
});
FB.getLoginStatus(function (response) {
    if (response.status === "connected") {
        FB.api("me/bookvote:download", "post", {
            book: "<?php echo "http://mysite/auction_details.php?name=$item_details["name"]&auction_id=$item_details["auction_id"]";?>",
            fb:explicitly_shared = "true" //? Is syntactically valid but creates a global
        }, //Missing a , here?

Upvotes: 3

Carlos Castillo
Carlos Castillo

Reputation: 907

Change this line:

book: "http://mysite/auction_details.php?name=' . $item_details["name"] . '&auction_id=' . $item_details["auction_id"] . '",

Upvotes: 0

Related Questions