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
Related
I have ajax that calls a php file called "fetch_quarter_limit.php" from template file.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
var quarter_limit = data['myVar'];
alert(quarter_limit);
}
});
In my .php file i have tried to return the session data as an array.
Fetched the required data, stored in session and formed an array.
$_SESSION['quarter_limit_mend'] = $quarterLimit;
$returnVal = array('myVar' => $_SESSION['quarter_limit_mend']);
echo $returnVal;
As shown in above ajax code part, i tried to fetch it, but all i am getting is "undefined" when i output the variable using alert.
Please help.
Ajax code updated, p2 :
Adding dataType is making code not to work.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
dataType: 'json',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
alert(data);
}
});
As #Tim mentioned i have added custom json encode function to my .php file.
It returns as expected {"myVar": 2}
echo array_to_json($returnVal);
This is returned from php file.
But not able to access in ajax code.
You're using echo on an array, which is not possible. As described in the PHP manual
echo outputs one or more strings.
Usually you'd use json_encode() on your array and then output it to the screen. But as you've commented you are using php < 5. First of all, if possible, you should consider to upgrade to PHP > 7, as this not only improves performance, it also improves security.
If you can't upgrade to a PHP version above PHP 5, then you can use workarounds. On this question there is already an answer for the workaround, and the workaround can be found on the PHP manual itself.
You should be able to use the returned JSON data.
Reply for after your edit
So you have your data as JSON now, but JS will still see it as a string. In your success function you still have to parse it.
success: function(data) {
jsonData = JSON.parse(data);
alert(jsonData.myVar);
}
I do have to add too that it is very insecure to continue using php < 7.3 (as of today, 24-02-2021)
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!
Hmm I have a little problem with that :
$.ajax({
type: 'POST',
data: {
name : 'aatrox'
},
dataType: "json",
async:false,
url: 'appliserv/testsendajax.php',
success: function(data){
console.log(data);
alert('good');
},
error: function(data){
console.log(data);
alert(fail);
}
});
the text in the alert is always fail ....
in my serv :
$text = $_POST['name'];
echo $text;
and I don't understand that. Thanks (sry if my english isn't good)
Your server-side script output plain text. So you have to change value of dataType option.
Change this:
dataType: "json"
to this:
dataType: "text"
Quite likely you're getting a parse error. This is because your ajax request is expecting JSON but you're are returning a plain string. Either return JSON from your PHP script or change the dataType to text:
dataType: "text",
Also be sure to change alert(fail); to:
alert('fail');
String literals must be delimited or variables have to be initialized before they are used.
You already got your answer, I just want to add that using
async: false
is a bad practice when dealing with ajax calls, it freezes your browser while waiting for the response.
If it's possible you should try to avoid this behavior and use
instead the ajax callbacks properly; however if you really want to block the UI you can try to use something like http://malsup.com/jquery/block/
Im trying to learn to use ajax at the moment, but unfortunately I cannot get it to success.
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_description : 'test'},
dataType: 'json',
success: function(json){
alert('pass');
},
error: function(json) {
alert('fail');
}
});
});
Here is the php function...
public function homepage_info() {
$json = array();
if (isset($this->request->post['info_description'])) {
echo $this->request->post['info_description'];
echo '<br /> test2';
}
$this->response->setOutput(json_encode($json));
}
However this always makes a fail alert instead of a pass one.
Am I missing something obvious here?
EDIT: Its finding the function ok, as in the console it is giving the correct response,
i.e.
test
test2
Thank you
If your dataType is set to json, anything returned that is not JSON will cause the ajax call to error out. Try sending some json back to the script... {"test":"abc"} or similar. I see a couple of calls to echo in your code, for example.
Not just this, but any PHP error/warning/notice printed to the browser will break calls.
Hint: you can generate valid JSON from PHP variables using json_encode().
You cannot combine an existing query string with data. Something like this should work (or at least be syntactically valid):
$.ajax({
url: 'index.php',
type: 'post',
data: {information:'information/information/homepage_info',info_description:'test'},
dataType: 'json',
success:function(json){
alert('pass');
},
error:function(json) {
alert('fail');
}
});
Also as was mentioned, anything that is not json will potentially cause an error, so you not echo those html components ... if anything, you print them.
Also, as a side note your dataType should be done server side with a header('Content-type: application/json'); declaration in index.php rather than in your jQuery script. Its guaranteed to be recognized as json that way, and also less Javascript code.
i took some interest in this script http://www.9lessons.info/2009/06/comment-system-with-jquery-ajax-and-php.html
and i see that the ajax calls commentajax.php.
what i want to do is to ignore that php, because i want to post to a json file and then get the response from the same file.
my server will use POST or PUT to put the data in the database, so there is no need for me to use php, just the syntax is killing me :)
i want to use :
$.ajax({
type: "POST",
url: "http://www.xxx.com/json",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
document.getElementById('comment').value='';
$("#name").focus();
$("#flash").hide();
}
});
but then how would the commentajax.php look like?
maybe replace the php with :
$.getJSON('http://www.xxx.com/json' , function(data) { ... });
any idea helps
Thanks.
edit1: i have the server-side script in place
If you have the server side scripting set up already, then what is the question again?
If you're asking how to handle the ajax call, then it's mostly a matter of looping through the JSON that you get back, and applying those values to the site in some manner. Pseudo code:
$.getJSON('http://www.xxx.com/json' , function(data) {
for(i=0; i<data.comment.length; i++) {
$(".commentTitle").html(data.comment[i].title);
$(".commentBody").html(data.comment[i].text);
}
});
If I am reading this correctly:
because i want to post to a json file and then get the response from the same file.
You are going to need some server side scripting in order to 'post' to the json file. How are you getting the data into the file.
You can 'read' the data file from the server, that's not a problem, it is a matter of getting the data into the file that you need the server side scripting for.