Home » Php » javascript – How to get UTF-8 format data through ajax

javascript – How to get UTF-8 format data through ajax

Posted by: admin July 12, 2020 Leave a comment


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>
function loadXMLDoc()
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  if (xmlhttp.readyState==4 && xmlhttp.status==200)

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


and this is my php script



                $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.

How to&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');


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


Try to use utf8-encode() like,

echo utf8_encode($sqlitedata);

If you are using jquery then use $.ajax() with contentType option which is default like,

function loadXMLDoc()
         contentType: "application/x-www-form-urlencoded;charset=utf-8",
         success: function(data){


between head tag place this

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

If you use any query in your php page place this before your query

mysql_query('SET CHARACTER SET utf8');
$result1 = mysql_query("SET NAMES utf8");