0

I tried to show a description from the YouTube API to p element but it's not working. I think the problem is with the quotes, single quote and new line; ie. "" , '' and \n.

This is the description text:

Another contestant attempts to overcome 'Head Case'! Will Daniel be able to "master" his fear of the unknown and be able to carry on singing?\n\nSubscribe for more awesome clips!\n\nSubscribe now!

$description = $vid["items"][0]["snippet"]["description"];
echo "<script>$('.pClass:nth-of-type(4)').text($description);</script>";

Note that it's working like this: $('.pClass:nth-of-type(4)').text('test');, but it's not working when read from the API.

5
  • you shouldn't mix PHP and JS like this - they execute differently and is harder to maintain. Just use ajax to send back-and-forth php data Commented May 14, 2019 at 16:23
  • but I want to set php variable in element using javascript or jquery do you have good way to that without echo ? Commented May 14, 2019 at 16:25
  • 1
    yeah .. ajax xD Commented May 14, 2019 at 16:26
  • 1
    There's little reason to make an entirely new AJAX request just to fetch a value that your page already has. But one thing you do need to do is elaborate on what "not working" means. What client-side code is emitting to the browser by this server-side code? In what way does it fail? Surely the lack of quotes in the client-side code is a problem, but what other problems might there also be? Examine the code in your browser and find out. Commented May 14, 2019 at 16:27
  • Can you give us example what is value of $description Commented May 14, 2019 at 16:37

1 Answer 1

3

You're outputting data to JavaScript, so you need to escape it in a way that will be safe for JavaScript to consume. Since JSON is a subset of JavaScript, you can use json_encode() for this purpose.

You should also avoid outputting JS in a double-quoted string; you can have problems with JS values being interpreted as PHP variables.

<?php
$description = json_encode($vid["items"][0]["snippet"]["description"]);
?>

<script>
    $('.pClass:nth-of-type(4)').text(<?=$description?>);
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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