Reputation: 2256
<!DOCTYPE html>
<html>
<head>
<title>WeekAPI</title>
<meta charset="utf-8">
</head>
<body>
Tag Value from Variable
<h1 id="txtDisplay">Please Wait..</h1>
Tag Value from API
<h1 id="txtResponse">Please Wait..<h1>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
var tag_value = "\uD83D\uDE05\uD83D\uDE00\uD83D\uDE02\uD83D\uDE2C\uD83D\uDE10\uD83D\uDE0E";
$("#txtDisplay").html(tag_value);
var api = "http://week.esy.es/api?id=140393107018&institute=039&branch=07&semester=7&callback=?";
$.getJSON(api, function(data) {
//response tag value is same as tag_value variable
$("#txtResponse").html(data.schedule.friday[0].tag);
});
</script>
</body>
</html>
API Response data
{
"ok": true,
"message": "Successful.",
"schedule": {
"monday": [
{
"type": "lecture",
"_id": 2,
"start": "11:32 AM",
"end": "11:32 AM",
"teacher": "KPP",
"subject": "Compiler Design",
"tag": ""
}
],
"tuesday": [],
"wednesday": [],
"thursday": [],
"friday": [
{
"type": "holiday",
"_id": 2,
"start": "09:30 AM",
"end": "10:21 AM",
"name": "\\u0928\\u0935\\u0930\\u093E\\u0924\\u094D\\u0930\\u093F",
"tag": "\\uD83D\\uDE05\\uD83D\\uDE00\\uD83D\\uDE02\\uD83D\\uDE2C\\uD83D\\uDE10\\uD83D\\uDE0E"
}
],
"saturday": [],
"sunday": []
}
}
1st scenario
unicode value of emoji stored into tag_value
variable
display using $("#txtDisplay").html(tag_value);
in txtDisplay portion.
it works fine
but when
2nd scenario retrieve tag value from api (value same as above)
display using $("#txtResponse").html(data.schedule.friday[0].tag);
in txtResponse portion.
it is fails to display emoji. it is display text instead.
Upvotes: 3
Views: 3811
Reputation: 2256
Got the solution after understand internal work of javascript.
javascript interpret unicode only when unicode string hardcoded between quotes.
so i used eval
function and created below code snippet to interpret unicode data runtime.
function interpret(s) {
return eval("(function(){ return '" + s + "'})()");
}
$.getJSON(api, function(data) {
$("#txtResponse").html( interpret( data.schedule.friday[0].tag ) );
});
Found another solution
at server side just added str_replace
function before printing response to replace \\ with \ in json
$response = json_encode($result);
echo str_replace( '\\\\' , '\\' , $response);
at client side
$.getJSON(api, function(data) {
$("#txtResponse").html( data.schedule.friday[0].tag );
});
Upvotes: 4