Solving European characters (Western charset) problem with Ajax and PHP

Today, I would like to tell you how to handle character set problem which occurs during the data fetched from PHP using Ajax mainly on the western characters(European charset).Lots of people asked me about this problem where these European charset is displayed in unreadable format after fetching it from ajax.

Problem with European Charset with Ajax and PHP

Suppose that I’ve the following code in PHP file, which output the string which contain the european characters.

<?php
  $str="€-accentuée";
  echo $str;
?>

Now, let’s use the Ajax from JavaScript using Jquery Code to fetch the data from PHP.

<script type="text/javascript">
$(function()
{
  $('#charsetdiv').load("test2.php");
});
</script>
<div id="charsetdiv"></div>

If you’ve not used jQuery then you might be wondering about the ajax code, you can check the benefits of jquery from this post and download free ebook of jQuery.

After getting value from Ajax, the division with id “charsetdiv”, let’s look at the output.

?-accentu?e

Solving western Character Set problem with Ajax and PHP

The above problem is occurred because of not defining proper charset to these European characters. We can solve this problem by sending the header which define the appropriate Character Set for these characters.Let’s see, how I solve this problem just adding the header which define the charset Windows-1256 – which support Arabic as well as European characters.

<?php
  header("Content-Type: text/html; charset=Windows-1256\n");
  $str="€-accentuée";
  echo $str;
?>

After adding that header in PHP, you’ll get the appropriate european characters in your Ajax enabled application.


Comments

One response to “Solving European characters (Western charset) problem with Ajax and PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *

*