Getting wrong charset output from AJAX - php

When I want to printout the output of jQuery AJAX, which has been recived from server. It doesn't show the right charset. What I want exactly is to get Š instead I am getting ?. All files script.js and server php proceed.php are saved in UTF-8 and set in UTF-8. Database is set to UTF-8 as well. I've tried most of the things.
In .js file for AJAX:
$.ajaxSetup({
url: "proceed.php", //file to procces data
ContentType : 'charset=UTF-8', // tried here
global: false,
type: "POST",
dataType: "html"
});
In .php file:
mysql_query("SET NAMES utf8");
$output = utf8_decode($sql_result);
All possible combinations.
UPDATE:
I've tried all proposed method in all possible variations and by using them, I don't get any response from server. The only time I get at least soem response is with settings mentioned above - literally. Setting AJAX dataType: "text/html" nor dataType: "application/html" doesn't help.
CODE:
PHP
if(!empty($_POST['select_had'])){
$zem = $_POST['select_had'];
$vysledek = mysql_query("SELECT typ_hadanky, jazyk FROM hlavolam RIGHT JOIN hadanka ON hlavolam.id_hlavolamu=hadanka.id_hlavolamu WHERE zeme_puvodu='$zem'");
$out = "";
while ($zaznam = mysql_fetch_array($vysledek)) {
$zaz = $zaznam['jazyk'];
$out .= "<option>".$zaz."</option>";
}
$vys = utf8_decode($out);
echo $vys;
}
jQuery:
$("#sel_had_zem").change(function(){
var select_had = $("#sel_had_zem option:selected").text();
console.log(select_had);
$.ajax({
data:{'select_had':select_had},
success: function(data){
console.log(data);
$("#sel_had_jaz option").nextAll().remove();
$("#sel_had_jaz").append(data);
},
error: function(){
alert('No server response');
}
});
});

You'll need to set the charset in your MySQL connection and not in the MySQL query. If you're using MySQLi then you can mysqli_set_charset() built-in PHP function. However, if you're using PDO then you can use it like this:
new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8;', USERNAME, PASSWORD);
You can find more information about the mysqli_set_charset() function here:
http://www.w3schools.com/php/func_mysqli_set_charset.asp
Note: Please, also ensure you've added the <meta charset="UTF-8"> in your HEAD tag.

Try changing the following..
dataType: 'html'
to
dataType: 'application/html'
keep
contentType: 'charset=utf8'
and add <?php header('Content-Type: application/html; charset=utf8'); ?> to the top of your pages.
For error reporting put error_reporting(E_ALL); at the top of your page as well. If any errors arise, post the code for that line, and post the error message in your OP post.
For your error
Resource interpreted as Document but transferred with MIME type application/html
In your request header, you have sent Content-Type: html which means that you'd like to interpret the response as HTML. Now if even server send you PDF files, your browser tries to understand it as HTML. That's the problem.
So need some info as to what exactly you're trying to send and what is the recieving end doing with this data?

You want to set the output from the PHP-page to UTF-8 and correct MIME-type:
mysql_query("SET NAMES utf8");
header( 'Content-Type: text/html; charset=utf-8' );
echo $sql_result;
exit;
This should fix the issue!

Related

json call allways returns an error

I want to perform a simple json call to a php file, but somehow it allways returns an error.
This is my html (the dataString is filled with form values):
$.ajax({
type: "POST",
url: "reghandle.php",
data: dataString,
dataType: "json",
success: function(result){
$("#modaltitle").html("Welcome");
$("#errorDetails").html(result.responseText);
$('#myModal').modal('show');
},
error: function(result){
$("#modaltitle").html("Error:");
$("#errorDetails").html(result.responseText);
$('#myModal').modal('show');
}
});
And my php file (I use $num_rows to produce an error or an succes):
if ($num_rows>0){
echo "error and blablabla";
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
return json_encode(array("error" => "bad table name"));
}else{
echo "ok";
header('Content-Type: application/json; charset=UTF-8');
return json_encode(array("success" => "blablabla"));
}
If I let my php file produce an error, the modal screen popsup with:
Title: Error
Errordetails: error and blablabla
(this is all correct)
And if I let my php file produce a success, the modal screen popsup with:
Title: Error (this should be a Welcome message)
Errordetails: ok
So obiously something goes wrong when returning a success from within my php file, I haven't got a clue what it is though.
because echo "error and blablabla"; and echo "ok"; is not json!
remove these .
echo "ok"; breaks it on two counts:
You have to output your HTTP headers before you output any content.
Outputting some free text before the JSON in a JSON document invalidates the JSON
You are returning the JSON (it isn't clear if you are returning it anywhere useful) instead of echoing it.
You are telling Jquery that only JSON responses from the server should be treated as successful, but your not sending a JSON response.
So, a few things to note here:
You shouldn't output (echo) anything before you set any headers, because the headers have already been sent and so cant be modified.
If you do set your headers to say the doc is json, then you should output some json on the page somewhere! (although it still has to be after the headers).
Your json_encode statement won't do anything as it only returns. It doesnt output the encoded json data onto the page anywhere.
In short, if you remove the current echo lines, then replace your returns with echos, then it should work.

Ajax sends wrong charset

Ajax is sending to PHP
Ĺ asija-kabina
Instead of
Šasija-kabina
While I did declare the charset everwhere.
In the head of the html file I've got this:
<meta charset="ISO-8859-2">
In the PHP file I've got this:
header('Content-Type: text/html; charset=latin2');
And this is my ajax function where "str" is a json array:
function updateField(str, id, prevvalue, value, vehicletype){
$.ajax({
type: "get",
url: "inc/ajax/form_rest.php",
data: { q:str, prevvalue:prevvalue, value:value, vehicletype:vehicletype },
contentType: "application/json;charset=latin2",
success: function(html) {
$('#'+id).html(html);
}
})
.done(function(){
$("#"+id).removeAttr("disabled");
if($("#"+id+" option").length == 2){
$("#"+id).val($("#"+id+" option:last-child").val()).change();
}
if($("#"+id+" option:last-child").val() == ""){
$("#"+id).attr("disabled", "disabled");
}
});
}
Nevertheless I am getting the wrong output. Can anyone help me with this?
I think you need to use the correct ISO name for the character set, e.g. change:
contentType: "application/json;charset=latin2",
to
contentType: "application/json;charset=ISO-8859-2",
I also think that using anything other than UTF-8 is going to get you in more trouble later in your project as json_encode in PHP really only supports UTF-8.
do you use an external javascript file for this?, I think you need also to set the character set for the inclusion of the javascript file
<script src="myscripts.js" charset="latin2"></script>
but I really recommend you to use UTF-8 both on server and client side scripts

JSON error(s) with php backend

I've never worked with JSON before and it's not going well...
I have a PHP script that returns a JSON array(is that the correct term?)
The script returns:
{"items":1000,"mitems":0,"donations":0,"total":1000}
NOTE: The script also sets the Content-Type to application/json
Here is my front-end javascript to handle that response:
function ajax(){
$.ajax({
url: '../ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function( data ){
// data.responseText is what you want to display, that's your error.
alert(data.responseText);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
When that function is called I get an alert with the following message:
{"items":1000,"mitems":0,"donations":0,"total":1000}
If everything was successful, I should get an alert that says success, right?
Can someone please tell me what is going on here?
Thank you!
This is the least documented thing in jquery what you need to do is alert the actual error in order to debug it. so do the following:
function my_ajax(){
$.ajax({
url: '/ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function(jqXHR, textStatus, errorThrown){
// data.responseText is what you want to display, that's your error.
alert(jqXHR+","+textStatus+","+errorThrown);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
So two things I've done:
Change the name of the function (ajax is kinda a bad name :S) and improved the error reporting.
You should be getting the alert "success" yes. So something is going wrong.
EDIT:
Just noticed another thing, I dont think "../" would be a great way to reference the url, usually its either "/foo/ajax" which will allow you to use this function on any page.
It could be that your PHP script returns an error status code and even though it prints out the correct result, it still fails. I tested your scripts on my system and I got the 'success' alert. Then I changed my PHP script to the following:
<?php
header('Content-type: application/json', true, 401);
echo '{"items":1000,"mitems":0,"donations":0,"total":1000}';
?>
Note that the third parameter of the header function sets the http response code to 401 - Even though the correct output is sent back to the client; officially, the request has failed because of that status code. After running this code, I got the exact same problem as you.
So in summary, there might be something in your script which is causing a non-fatal error which doesn't show in the output of the script.
Are you defining the MIME type in your HTTP response?
Try adding a Content-type header to the output of your script.
<?php
...
$output = json_encode(...);
header('Content-type: application/json');
echo $output;
...
?>
You can also try using the mimeType parameter in your $.ajax() call to override the response type.
http://api.jquery.com/jQuery.ajax
Are you running your PHP scripts under Apache or on their own (chmod u+x on the script)? You probably need to use a PHP framework such as Zend, CodeIgniter or CakePHP and define a controller action that handles your AJAX request to have a proper HTTP response.
As the guy above me said, you should be using the json_encode(); function in PHP then echo'ing that output.
Make sure you encode an array though:
<?
$send = array(
'items' => '1000',
'mitems' => '0',
'donations' => '0',
'total' => '1000',
);
echo json_encode($send);
?>

jQuery dataType:

I have an odd problem regarding jQuery dataType.
I have a very simple PHP program that returns (echo's) an XML file (string). Looks like this:
$xmlFile = "sampleXMLFile.xml";
$xml = simplexml_load_file($xmlFile);
echo $xml->saveXML();
My client/javascript code calls the php program via ajax:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "myPHPFile.php",
dataType: "xml",
success: myCompleteFunction,
complete: mySuccessFunction,
failure: function(data) {
alert("Problem getting XML");
} });
});
The "myCompleteFunction" takes the XML and simply writes the first node into a div element, like this:
function myCompleteFunction(xml)
{
$(xml).find("Row").each(function()
{
$("#result3").append($(this).attr("myrow"));
});
}
OK - in IE 8, this works fine. In Firefox and Chrome I get no results. However, if I change the dataType to "html" I get correct results in Firefox and Chrome and then get no results in IE.'
Continue to go crazy with this. Do I actually need to put conditional logic for the browsers?
The dataType: option explained in the jQuery manual seems clear enough. I even tried to leave dataType out
(per manual: If none is specified, jQuery will try to infer it based on the MIME
type of the response)
I also tried multiple types - e.g. "text xml". No good.
Anyone ever run into this problem? Any direction would be appreciated.
Thank you.
p.s. I know I can read an XML file in jQuery. The resultant XML from the PHP program would be substantially more involved. I only used that as an example.
Updated:
Well, I saw Phil's comment about producing something before XML data sent. There was certainly nothing obvious. I removed a blank line above my first <?php line. This has somehow worked! Still seems odd to me. So my new, tighter PHP code is now:
<?php
// Load XML
$xmlFile = "sample.xml";
$xml = simplexml_load_file($xmlFile);
header('Content-type: text/xml');
echo $xml->saveXML();
?>
I will also pay mind to your other suggestion about properly handling jQuery.ajax() callbacks. Thanks.
I very much appreciate your help w/this!!
Stick with the "xml" dataType and add this to your PHP file before the echo...
header('Content-type: text/xml');
Also, you seem to be mixing up some of the jQuery.ajax() callbacks.
Use success to handle the returned data.
Use error(jqXHR, textStatus, errorThrown) (not failure) to handle HTTP errors
Use complete to execute some tasks after success and error callbacks have executed

JSON.parse fails in jQuery when PHP response-header contains "application/json"

I'm getting a bit of a headache trying to figure this one out. To request some json-data from a PHP-script via Ajax, I'm using the jQuery function:
$.ajax({
type: 'GET',
cache: 'false',
url: ajaxUrl,
data: dataString,
success: updatePage
});
If I don't set content-type in the PHP header to:
header('Content-type: application/json');
Then my response from the server looks like this:
{"content":"new content"}
And the content-type is automatically set to text/html. When dataType in the jQuery ajax options is unset, it uses a default of 'intelligent guessing'. I'm strongly assuming that jQuery recognizes the response-data as json because updatePage is parsed an object. updatePage uses the JSON js library(json2.js), and does this:
function updatePage(data) {
$dataObj = JSON.parse(data);
}
When the function is called upon ajax succes, everything works fine. No errors.
Here's the strange thing, if I set my header to application/json as above, JSON.parse suddenly reports an error. The exact same error happens if i set my dataType to 'json' in the jQuery ajax request. The response I get from the PHP script when changing these things looks exactly like the one above. The error looks like this in Firebug:
JSON.parse
$dataObj = JSON.parse(data);
Kind of a long one, sorry, but If anyone knows what is wrong their help is greatly appreciated. Thanks for your time.
It's because you end up trying to double-parse the return value.
Both the explicit json data type and usage of the application/json MIME type cause jQuery to parse the returned string into a JavaScript object for you.
So, your usage of JSON.parse(), in these cases, is superfluous.

Categories