Special character in json response is not parsed in IE - javascript

I am using the following code in the js file to get the response back from servlet as follows:
The code is as follows:
function(response){
$("#city").attr("disabled", false);
var select = $('#cityList');
select.find('option').remove();
var parsedObject = JSON.parse(response);
for(var city in parsedObject){
$('<option>').val(parsedObject[city].cityName).text(parsedObject[city].cityName).appendTo(select);}}
In Internet Explorer, I get an error stating "Invalid Character" in the line:
var parsedObject = JSON.parse(response);
After checking the response, I noticed an object where the city name is causing an issue:
{"countryId":0,"stateId":0,"cityId":4046,"cityName":"Belle Vall�}
The correct city name is Belle Vallée. It seems IE is not allowing to parse this city name and hence, the drop down displays no city value.
In the Google Chrome, I do see all city values however, the above stated city name is not displayed properly as shown below:
I came across a solution to add the following code in the header to allow chrome to display special characters properly but it didn't work for me.
< meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
The following code is being executed on the servlet side:
This is how my new function with ajax call looks like:
function changeState(){
var state = $("input#province").val();
$.ajax({
type: "GET",
url : 'LocationServlet',
dataType : "json",
contentType: "application/json; charset=utf-8",
data : {"stateName": state},
success : function(response){
$("#city").attr("disabled", false);
var select = $('#cityList');
select.find('option').remove();
var parsedObject = JSON.parse(response);
for(var city in parsedObject){
$('<option>').val(parsedObject[city].cityName).text(parsedObject[city].cityName).appendTo(select);
}
}
});
}

It seems that the response you have received has already been parsed.
Instead of the line:
var parsedObject = JSON.parse(response);
Try using "response" received as a parsed object.

Add
response.setCharacterEncoding("UTF-8");
If your response come from an ajax call. Just check the content-type of your ajax call.
$.ajax({
type: "GET",
dataType : "json",
contentType: "application/json; charset=utf-8",
...
})

Related

AJAX POST of tinyMCE contents - Character encoding of table entities

I'm using the tinyMCE editor plugin in my webpage.
When I use a simple HTML page post to post the contents to the backend PHP and save them to a database or file, all seems OK.
When I try to do the same using an AJAX post, I am finding it impossible to prevent encoding issues.
In particular (I'll escape it here) \&\n\b\s\p\; is being converted to  and a "-" character is being converted to �
I've tried a few suggestions but with little luck.
The suggestion is that it is either an issue with my charset or encoding.
My save function is as follows:
function letterSave(newfile,fname){
var newDate = new Date;
var uniq=newDate.getTime();
var input = $('#myTextareastdletter');
var contents=input.val();
var context='<?=(!strcmp($sessobj->mode,"SA_ViewAbs")?"A":"S");?>';
// alert(fname);
$.ajax({
type: "POST",
url: '<?=auto_version("./SVajaxSaveDocContents.php")?>?duff='+uniq,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {'S_sessid' : '<?=$sessobj->sessionid?>', 'context' : context, 'contents' : encodeURIComponent(contents), 'fname' : fname, 'newfile' : newfile},
success: function(data){
data = JSON.parse(data);
fname=data[0];
newLetterList=data[1];
if (fname != 'FAIL') {
alert ('OK: Letter Contents Saved to File ('+fname+').');
var versionOutput = $('#popupOutput');
versionOutput.html('');
var box = $('#popupDisplay');
var cover=$('#coverDiv');
box.css({
display:"none"
});
cover.css({
display:"none"
});
var letterOutput = $('#AbsenceLetters');
letterOutput.html(newLetterList);
} else {
alert ('Sorry: Failed to Save Letter Contents!');
}
},
error: function(data){
alert ('Sorry: Failed to Save Letter Contents!');
// console.log(data);
// console.log('error');
}
});
}
As you can see, I've been playing with setting the contentType and using encodeURIComponent().
Any help would be appreciated.
Cheers
In order to avoid these encoding issues, don't use .val on the textarea that the tinyMCE instance is attached to. Instead, you can utilize tinyMCE's built-in getContent method like so:
tinyMCEInstance.getContent()

get alphabat instead of word jquery ajax

I wan't to get string instead of word. how can i do this.
php file code
<?php
$countries = array("Afghanistan", "Albania");
$response=array("countries"=>$countries);
echo json_encode($response);
?>
html file
$(document).ready(function(){
$("button").click(function(
$.ajax({
type:'GET',
url:'./countries.php',
data:{countries:true},
cache:false,
async:false,
success:function(data){
var str="";
for(i=0;i<data.length;i++)
{$("tbody.new").append("<tr><td>" + data[i] + "</td><td></td> <tr>");}
result is like this a f g a every word is separate line
You haven't specified the accepted data type in ajax options object. That's why you are getting a json string instead of parced json data.
Change your code as shown below:
$(document).ready(function(){
$("button").click(function(
$.ajax({
type:'GET',
url:'./countries.php',
data:{countries:true},
dataType: 'json',
cache:false,
async: true,
success:function(data){
var str = "";
for (i = 0; i < data["countries"].length; i++){
$("tbody.new").append("<tr><td>" + data["countries"][i] + "</td><td></td><tr>");
}
}
}
You need to set dataType:'json' since you aren't setting appropriate content type header on server.
This will tell $ajax to parse response to array or object in success callback.
Then you want to access the proper property of the response object which will be data.countries which is an array
Also async:false is a terrible practice. It should never ever be used and you should be seeing deprecation warnings in browser console

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

Jquery - parse XML received from URL

I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.

JSON Response {"d":"128.00"} but displaying "128"

I have been working on a shopping cart that the user can add/remove order items as they please and am returning an updated sub-total via a webservice using jQuery $.ajax
Here is how I am calling the webservice and setting the sub-total with the response.
//perform the ajax call
$.ajax({
url: p,
data: '{' + s + '}',
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#cartRow" + orderID).find(".subTotal").text(sTotal);
},
failure: function() {
//if the orer was not saved
//console.log('Error: Order not deleted');
}
});
The response I am getting seems perfectly fine:
{"d":"128.00"}
When I display the total on the page it displays as 128 rather than 128.00
I am fully sure it is something very simple and silly but I am so deep into it now I need someone with a fresh brain to help me out!!
Cheers :)
EDIT
I am also using $.ajaxSetup to set the correct contentType:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data) {
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
});
That is because the value is treated as a number, while you want it treated as a string.
When you are using '.. .text(sTotal)', you are actually calling the .toString() method on the Number object wrapping the primitive sTotal. And since this is a whole number, it displays it without decimals.
You need to use a format the number as a string prior to calling .text(foo) for the number to be formatted like that.
This will give you two decimals
var a=1/3;
a = a.toString();
switch(a.lastIndexOf(".")){
case -1:
a+=".00";
break;
case a.length-2:
a+="0";
break;
default:
a=a.substring(0, a.indexOf(".") + 3);
}
alert(a);
I don't see anywhere in this code where you access the d property of the response.
Perhaps you mean to do this?
$("#cartRow" + orderID).find(".subTotal").text(sTotal.d);
// --------------------------------------------------^^
EDIT
Ok, I see the problem. You're returning JSON but not defining a dataType in the $.ajax() call. This means that jQuery sees your application/json mimetype and interprets the response as JSON. 128.00 in JSON is a Number, not a String. However, "128.00" would be a String.
In order to keep this working, You need to format the response before printing it (as others have suggested), or adjust your endpoint to return a valid JSON string.
Here's my test to prove the solution
<div id="test">
Subtotal <span class="subTotal"></span>
</div>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" charset="utf-8">
google.load("jquery", "1.4.2");
</script>
<script type="text/javascript" charset="utf-8">
$.ajax({
url: 'test.php',
data: {},
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#test").find(".subTotal").text(sTotal);
}
});
</script>
and test.php
<?php
header( 'Content-type: application/json' );
echo '128.00';
Output
Subtotal 128
But when I change test.php to be this
<?php
header( 'Content-type: application/json' );
echo '"128.00"';
The expected output is generated
Subtotal 128.00
Or, you could alternatively tell jQuery to treat the response as text by specifying a dataType parameter, for example
$.ajax({
url: 'test.php',
data: {},
dataType: 'text', // <---- here
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#test").find(".subTotal").text(sTotal);
}
});
EDIT 2
Ok, after messing with this some more, I see what's going on. The dataFilter handler you defined converts the response into JSON itself, and in this case, returns the string 128.00. However, jQuery still applies the intellgent-guessed dataType (which is JSON) to this value before sending it to the success handler.
There are a multitude of ways to fix this, all of which depend on what other AJAX calls your application relies on this setup for. The quick-fix I applied in my test was to do this
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
// define the text data type so that we return data.d, jQuery doesn't parse it as JSON again
dataType: 'text',
dataFilter: function(data) {
data = $.parseJSON( data ); // Use jQuery's parsing
if (data.hasOwnProperty('d'))
{
return data.d;
}else{
return data;
}
}
});
But that may not work across the board for you
Please try this:
$("#cartRow" + orderID).find(".subTotal").text(sTotal.toFixed(2));
HTH

Categories

Resources