Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get UTF-8 format data through ajax

Sorry if i am asking a silly question but i really need a solution for it.I am requesting for some data using ajax and the script is

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
$url='http://localhost/path/to/the/php/script';
xmlhttp.open("GET",$url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

and this is my php script

<?php 

$sqlurl='/path/to/my/file';

 if(file_exists($sqlurl))
            {
                $sqlitedata= file_get_contents($sqlurl);

       echo $sqlitedata;
            }
            else {

           echo 'the file is not available right now';
             } 
?>

Now the problem is that the data in my file is in the UTF-8 format but when i try to get it through ajax then what i get is a series of question marks (??????) . How can i request for the data through ajax in the same format in which it originally exists.

like image 732
Let me see Avatar asked Nov 11 '13 04:11

Let me see


1 Answers

asuming your file is indeed a xml file, assuming the page making the request is utf8,

then before you echo anything in your php file :

<?php header("Content-Type: application/xml; charset=utf-8"); ?>

for extra safety in your xml :

<?xml version="1.0" encoding="UTF-8"?>

edit you can do that as well :

header('Content-type: text/xml');

with

<?xml version="1.0" encoding="UTF-8"?>
like image 141
mikakun Avatar answered Sep 23 '22 16:09

mikakun