Display special characters in javascript - javascript

I am using the Google Places API to supply my application with a list of cities, countries, etc for a dropdown menu. I use an AJAX request to a file containing this code:
$results = file_get_contents("https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(regions)&language=EN&offset=4&key=" . $key . "&input=" . $input);
$decode = json_decode($results, true);
foreach($decode["predictions"] as $value){
$json_array[] = $value["description"];
}
echo json_encode($json_array);
Everything seems to work okay on this side of things, however when the JSON is returned to the AJAX application, some of the characters appear incorrectly. For example, the "ã" in "São Paulo" appears as ",," or "S,,o Paulo" when I try to display the results. If I alert the result, the characters do display correctly in the pop-up - so I seem to be missing something when I give the results to the javascript to display in the drop down. (What also is irritating is that the incorrectly coded results end up getting entered into my database when the user selects from the drop down.)
I have tried encoding each string with "utf8_encode()" before I add it to "$json_array" (in the PHP file, of course), but this only seems to complicate things - it appears that the results are double-encoded or something when it is finally displayed in the javascript.
Also, I should note that the web page has the UTF-8 charset in the meta tag.
As a follow-up:
I created a simple HTML page which in which I displayed "ã" in a div, and it did show up properly. I also used jQuery to display the same character in another div on page load, and this too showed up correctly. And I didn't even need to set the encoding on that page. So I can only assume, because this test page is plain vanilla HTML, that the problem is coming from my PHP set-up.
I have added the following to the head of another PHP tests page:
mb_internal_encoding("UTF-8");
mb_http_output("UTF-8");
mb_http_input("UTF-8");
mb_language("uni");
mb_regex_encoding("UTF-8");
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=UTF-8");
but I am still seeing the characters incorrectly displayed. So to this point I have added the above, updated the default_encoding to UTF-8 in php.ini, and checked that the meta tag specifies UTF-8. This is really starting to irritate me now!

use one of either header:
header('Content-type: application/json');
header('Content-Type: text/html; charset=UTF-8);
work for me in case of Arabic language.

It might be that the webpage is not recognizing the character. To fix this, use HTML code for this character.
For example, the HTML code for ã is ã.
You can find more information on this here.
Check for special characters in your PHP string and convert these.
$mystring = 'São Paulo';
$findme = 'ã';
$pos = strpos($mystring, $findme);
if ($pos != false) $findme = "ã";

This was the dumbest thing... but I learned a lot about character encoding along the way. It turns out (and I didn't mention this at all because it just didn't seem relevant) that the Helvetica fonts in Bootstrap cannot display these special characters. Yeah, wtf? I had every possible encoding option set to "UTF-8", and all along it was just the stupid CSS font selection. So in the end I just changed the font family to "Arial" and instantly the problem was solved.
Thank to everyone for the input.

Related

How to concatenate a variable in a document.location.href path?

I have a php $_SESSION passing the name of a target directory, that is different from situation to situation. I have a javascript function to execute a file with the same name but in several different directories, depending on the string passed with $_SESSION. My code is:
<?PHP
$where = $_SESSION["where"];
?>
<script>
var where = "<?php echo $where;?>";
function goToThere() {
document.location.href = where + "/file_to_execute.php";
}
</script>
<body>
<button class="buttongreen" onclick="goToThere()">proceed</button>
</body>
Say the content of $where is "dir_a". Then clicking on buttongreen might launch function goToThere, thus going to page "dir_a/file_to_execute.php". The problem is that the goToThere function simply does not do anything. I've tried different sequences to concatenate the variable and the string, with various combinations of quotation marks, without success.
What am I doing wrong?
As stated, your code is applicable to what you are trying to do. The issue lies in the "$_SESSION['where']"
Either...
(1) You have a forward slash at the end of $_SESSION['where'] and you are adding another forward slash when concatenating.
(2) You are not doing "session_start();"
(3) The script code is not being incorporated into the body nor header (I'm not quite sure about this, but as I see it, the script code really is in no man's land so maybe???)
(4) The $_SESSION['where'] is simply not being saved
(5) The $_SESSION['where'] is simply empty
As it stands though, your code is valid as a proof-of-concept for what you are aiming to do

How to correctly handle UTF8 results from a MYSQL database with PHP? [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 6 years ago.
For a few days now I've been looking for a solution to display UTF8 on my
webpage.
The character currently causing trouble is į (unicode: \u012f decimal: 303) however,
there are over 10,000 records in my database and I cannot guarantee that all others are displaying correctly.
So I'm looking for a solution that should cover all characters.
The į is displaying as a ? in the HTML.
My setup is a HTML page, which uses AJAX to send a request to a PHP file.
The PHP then queries a MYSQL database to find a specific entry,
it then takes a lithuanian word from that entry and echoes it as a response to AJAX.
Back in the Javascript, the response is set as the innerHTML of a HTML element.
This current setup is not using JQuery.
Below is my progress on attempting to fix the issue.
First, I verified that all files I was working with are correctly encoded to UTF8, not UTF8BOM.
Then I opened the MYSQL database in phpMyAdmin to view the entries.
Seeing characters replaced with ? in the entries, I done some research and found the database had the wrong collation.
After changing the collation to utf8_general_ci for the database/table nothing changed, so I looked into it further and found that changing it for individual columns of a table was another solution.
This worked and my database is now displaying the characters correctly.
Next the character š (unicode: \u0161 decimal: 353) would not display in my webpage,
I fixed this by using the following code in PHP which I found on stackoverflow.
function encode_string($string){
$encoded = "";
for ($n=0;$n<strlen($string);$n++){
$check = htmlentities($string[$n],ENT_QUOTES);
$string[$n] == $check ? $encoded .= "&#".ord($string[$n]).";" : $encoded .= $check;
}
return $encoded;
}
I can't say I completely understand this code but it caused the character š to display correctly when it got to my HTML.
However this did not work for the character į.
I have also tried $conn->set_charset('utf8'); to set the connection to use utf8 however this resulted in į being displayed
as į instead, same result for $conn->query("SET NAMES UTF8;");
I have found that hardcoding the į into the Javascript or PHP, allow it to be sent back and displayed correctly, for example echo "į"; works.
So I believe the issue may be related to the database or in the PHP before the echo.
However I don't have the knowledge to identify the problem.
Here is my php code below:
<?php
header('Content-Type: text/html charset=utf-8');
//Connection to database is made. Referred to as $conn
$sql = "SELECT * FROM Words";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//Loop through the results to find a word with the status of 1
while($row = $result->fetch_assoc()) {
$status = $row["status"];
if($status == 1){
//respond to AJAX with the word
$ltword = trim($row["lt"]);
echo utf8_encode(encode_string($ltword));
//Has also been tested as
//echo encode_string($ltword);
//with no noticeable difference.
break;
}
}
}
function encode_string($string){
$encoded = "";
for ($n=0;$n<strlen($string);$n++){
$check = htmlentities($string[$n],ENT_QUOTES);
$string[$n] == $check ? $encoded .= "&#".ord($string[$n]).";" : $encoded .= $check;
}
return $encoded;
}
?>
At the core my question is, given my current setup,
how do I correctly get an encoded UTF8 character from my database to display on my webpage?
EDIT:
The mb_check_encoding() function of php, verifies that the data received from the database is valid utf8.
php.ini is using utf8 as it's default charset.
Using $conn->character_set_name(); returns the result latin1.
Using $conn->set_charset("utf8"); causes it return utf8, however į is then displayed as į which is still incorrect.
If you're using mysqli, you can call set_charset():
$mysqli->set_charset('utf8mb4'); // object oriented style
mysqli_set_charset($link, 'utf8mb4'); // procedural style
in your case problem was collation, which was modified later. As a good practice try to set table collation as well as column collation same ie. utf8_unicode_ci (general is faster but unicode is much better for sort/display).
Now coming back to problem, the problem lies with already added data which was stored wrong due to non proper collation. For that you need to look & resolve method as you cant be sure it was stored properly.
If you have UTF8 end to end (db > connection > php) you should not have to echo utf8_encode. Just echo the variable and it should display correctly.
Most likely, the character is is messed up in the database because it's still in the original encoding. Try updating the contents of the database with native UTF8 characters now that the collation has been fixed and it should work.
So most likey you will need the $conn->set_charset('utf8') too.

assigning php return value to a javascript variable

I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;

How do I get character entities to render (PHP pulling from database to display in Fullcalendar)?

I'm using PHP to pull posts from Wordpress (WP_Query()) to generate Fullcalendar event strings. All's working swell except character entities (specifically apostrophes), which are in the post's Title field (as apostrophes), are displaying on the webpage as "’". I thought maybe there's some double decoding going on somewhere, so I tried running the variable through html_entity_decode(), as well as htmlspecialchars_decode(), with no luck. Thanks for any help!
<?php
$the_film = ': '.strtoupper(get_the_title($filmID));
...
echo '{"id":"'.get_the_ID().'","title":"'.$the_city.$the_film.'","start":"'.$start.'","color":"'.$color.'","textColor":"'.$textColor.'","url":"'.$filmlink.'","moderator":"'.$moderator.'","guest":"'.$guest.'"},';
?>
Thanks for the nudge, Henrique. Your confidence in me proved worthy. I messed around with things a bit more and because I was using .text() rather than .html() in rendering my FC events, the character entities weren't being decoded.

Storing HTML in a Javascript Variable

I am currently coding a website that will allow a user to input data into a MySQL database using a WYSIWYG editor. The data stores into the database without a problem and I can query it using PHP and display it on my webpage.
Up to this point everything is working ok until I try to move the HTML stored in the MySQL database into a javascript variable. I was able to get it working using CDATA[], but not for every browser. It works in Firefox, but not IE or Chrome. I am looking for a solution that will be able to work in all of the browsers. Any help would be greatly appreciated.
Since you're using PHP:
<script>
var foo = <?php echo json_encode($htmlFromDatabase); ?>
</script>
The json_encode method, while normally used for encoding JSON objects, is also useful for converting other PHP variables (like strings) to their JavaScript equivalents.
"Safefy" your code, like this
str_replace( array("\r", "\r\n", "\n", "\t"), '', str_replace('"','\"',$str));
The above function clears linebreaks, and tabs so that your code appears in one line. If it breaks into more than one line, then it cannot be parsed as a string in JS and an error is thrown. Also we are escaping " to \", maybe there are more string replacements that need to take place, it depends in your content.
and inline it in javascript,
//<![CDATA[
var myHtml = <?php echo '"'.$stuff.'"'; ?>;
//]]>
keep in mind the '"' part so that it appears like this var myHtml = "test";

Categories