Search code examples
javascriptphpjquerysingle-quotes

How to escape JSON values with Single Quotes(apostrophe) within JavaScript function


When the data is passed (not mixed with any special characters) to the JavaScript function, then it would console the data. But when the data is passed with a single quote result's out an error in the console

  1. "ask_game_name":"FIFA 17" - It would print without any errors

  2. "ask_game_name":"Assassin's Creed IV" - It would result as "Uncaught SyntaxError: Invalid or unexpected token" exactly pointing at the apostrophe

Here is the below snippets of code followed while generating such an error in PHP

onclick='UserQueries(<?php echo json_encode($askInfoData); ?>)' 

Data will be passed inside the JavaScript as an argument parameter and displays the JSON values

<script type="text/javascript">

function UserQueries(data)  
{
    console.log(data);
}

</script>

Here is what the Data consoled after passing it into JS.

UserQueries({"ask_info_id":"1","ask_user_id":"1","ask_game_name":"FIFA 17","username":"Nishanth","avatar":"1800766906.png"})

UserQueries({"ask_info_id":"2","ask_game_id":"3","ask_game_name":"Assassin

How should I need to display the values in the console containing single quotes values?


Solution

  • To make a string safe to insert into an HTML attribute:

    • Use htmlspecialchars
    • Use " to delimit the attribute value, or set the option on htmlspecialchars to include ' in the escaped data.

    Such:

    onclick="UserQueries(<?php echo htmlspecialchars(json_encode($askInfoData)); ?>)"