Displaying accented character in Javascript - javascript

I am having problem displaying accented character in my app; It is showing ⛽ instead of ó. The string is coming from a json file retrieved from a server. Here are the technical details:
JSON: (This is the object being retrieved from the server)
notice the 3rd key "Relación" the letter "o" is accented.
[
{
"key": "Canales"
},
{
"key": "Productos"
},
{
"key": "Relación con el ejecutivo"
}
]
Ajax (here is the code to retrieve the information)
notice I already added charset=utf-8 as most answers suggest
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(uri){
alert("clintg test: " + JSON.stringify(uri));
}
}
Alert: (as you can see, it is just showing a box symbol where it's supposed to be -> ó)

To give more detail to #georg 's advice that helped me solve this issue:
Since I can't change the server side scripts, I adjusted the code on my side.
I changed the charset in my ajax request to ISO-8859-1, but since the default charset of ajax is utf-8, I had to override the charset with $.ajax.beforeSend:
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json; charset=iso-8859-1",
success: function(uri){
alert("clintg test: " + JSON.stringify(uri));
},
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('application/json;charset=iso-8859-1');
}
}
Here's a link to the question that helped me figure out and override the charset: Jquery ignores encoding ISO-8859-1

Related

How to Add filter on the REST API Query to view the answers from QnAmaker?

I'm using the following code in my chat bot (using v4 azure MS bot framework), to query the question and answers (Client side code - using plain JavaScript and J Query),
function generateAnswer()
{
var question = {
question: "will you marry me"
}
$.ajax({
type: "POST",
url: "https://YourEndPointURL/qnamaker/knowledgebases/eb895acb-e034-4f7c-asda7c-1955458ecec6/generateAnswer&$filter=source eq 'Editorial'",
data: JSON.stringify(question),
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization','EndpointKey c44444_Your_Endpoint_Key_4556');
},
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
console.log(data.answers[0].answer);
}
});
}
while using this code, i"m getting the following error response
The resource you are looking for has been removed, had its name
changed, or is temporarily unavailable.
So please help me with the correct syntax to apply filter for my query.
According to https://learn.microsoft.com/en-us/azure/cognitive-services/qnamaker/how-to/metadata-generateanswer-usage, you need to specify filters in the body (the data property)
function generateAnswer()
{
var data = {
question: "will you marry me",
strictFilters: [
{
"name": "source",
"value": "Editorial"
}],
}
$.ajax({
type: "POST",
url: "https://YourEndPointURL/qnamaker/knowledgebases/eb895acb-e034-4f7c-asda7c-1955458ecec6/generateAnswer",
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization','EndpointKey c44444_Your_Endpoint_Key_4556');
},
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
console.log(data.answers[0].answer);
}
});
}
Moreover, you are missing 2 things:
your hostname, to replace YourEndPointURL
endpoint key, to replace c44444_Your_Endpoint_Key_4556

Configure / Change JQuery AJAX Encoding

I am making a basic PATCH call like this one:
.ajax({
url: "/foo/bar/"
type: "PATCH",
dataType: 'json',
data: {
"foo": "foosball",
"bar": "bars on bars"
},
...
});
Jquery automatically encodes the data, which leaves "bars on bars" like "bars+on+bars". Is there a way to change the encoding so that spaces are replaces with %20 rather than pluses?
I've noticed this thread that didn't seem to lead anywhere.
I've also taken note of encodeURI and encodeURIComponent but haven't gotten either to work. Both seem to result in the string being double encoded, leaving me with bars%2520on%2520bars
summary:
What I start with:
... "bars on bars" ...
What the received data looks like after jquery encodes the request:
"bars+on+bars"
What I need the received data to look like:
"bars%20on%20bars"
How about use a variable and pass that to data.
var d={
"foo": "foosball",
"bar": "bars on bars"
}
d.bar=encodeURI(d.bar);
.ajax({
url: "/foo/bar/"
type: "PATCH",
dataType: 'json',
data: d,
...
});
Still wish there was a better way, but I ended up using this plugin from this website.
jQuery.extend({
postJSON: function(url, data, callback) {
return jQuery.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
This forces my api to parse the body as a string into a dict/json. Hopefully in a few years someone can come along with a better solution.

AJAX to asmx (VB) webmethod - GET with parameters

I've been reading a lot of questions about this error, but just can't seem to get around it (it's incredible how many questions can be found on the web on this topic!!). Let me be straight:
test.asmx
'Simple POST (obviously with parameters)
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json)>
Public Function TestarPost(ByVal Valor as String) As String
Dim x
End Function
'Simple GET - no parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function Testar() As String
return "ok ;>D"
End Function
'GET with parameters
<WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function TestarGet(ByVal Valor as String) As String
return Valor
End Function
Trying it out in js console window:
obj = { Valor: "x" }
$.ajax({
type: "POST",
url: "test.asmx/TestarPost",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success!
$.ajax({
type: "GET",
url: "ServerSide.asmx/Testar",
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Success! Returns correctly data in JSON format
$.ajax({
type: "GET",
url: "test.asmx/TestarGet",
dataType: "json",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
success: function(ret) {
console.log(ret.d);
},
error: function(xhr,textStatus,errorThrown) {
console.log(xhr.status + "||" + xhr.responseText);
}
});
Fails! Doing the same as in Post
The message error is "Invalid web service call, missing value for parameter: \u0027Valor\u0027." Also fails if I send object literal ("Invalide JSON primitive"). However, if I access URL .../ServerSide.asmx/TestarGet?Valor=x, it returns "opa" (maybe a clue?)
What I don't get (pardon the pun) is why, since it's the same as in POST. Maybe because the POST isn't affecting anything and I can't see the result (but it returns no errors, at least).
My goal is to create a function serverSide(asmxMethod, obj) to make a generalized bridge between client and server functions.
I've found a solution (but not an answer). According to a friend, GET doesn't accept json parameters. Unfortunately, even if I send dataType: "text" it fails.
The solution is to use always POST. POST is also able to return data (didn't know that). So with the POST example I can send and receive data in json format without a problem.

ajax post truncating leading zero's

I have the following code:
$.ajax({
type: "Post",
url: 'http://example.com/jambo',
contentType: "application/json",
data: String(' ' + $('InputTextBox').val()),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
The value in InputTextBox has leading 0's but when this is posted to the url the leading 0's are truncated.
When sending json to a server, you should use the built-in JSON.stringify method to create json rather than creating it manually.
$.ajax({
type: "Post",
url: 'http://example.com/jambo',
contentType: "application/json",
data: JSON.stringify($('InputTextBox').val()),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
This will result in sending "0005" instead of 0005, which when parsed, will be converted back into the string rather than a number which will lose the leading zeros.
Testing the code on this page;
$.ajax({
type: "Post",
url: '/test',
contentType: "application/json",
data: String(' 004'),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
obviously alerts the 404 page but in the net tab of Chrome and Firefox shows the data is sent correctly ' 004'.
Please re ask your question with the code on the server, as the issue is not client side.
As Kevin B noted ' 004' is a type numeric according to the JSON specification
so if you want the zeros and want to use a JSON library on the server sent the data as '" 004"' or use JSON.stringify(' 004').
Removing contentType: "application/json", in my ajax call fixed the issue for me
Reason:-
contentType: "application/json", will get the values first converted to numbers as it tries to parse your data to JSON. Removing this line from your ajax call will stop the parsing of data.
Note : The parsing will happen not only in your data you are POSTing, but also it will parse the queryStrings in your URL when you use GET method

ajax json adding trailing colon

var mydata = {
"one": {
"brand": "acer",
"cost": "212132"
}
}
$.ajax({
url: 'http://localhost',
type: 'post',
dataType: 'json',
data: JSON.stringify(mydata)
});
Above code is adding a colon to the data when i view the form send data in chrome dev tools. Is there anything wrong with the request?
You are viewing application/x-www-form-urlencoded parsed data. So Chrome is trying to establish key value pairs. Click "view source" near the "Form Data" heading in the network tab view. You will see your JSON without the colon.
Was the same for me. I did not see the colon when viewing source. BUT it did not work.
My solution was to add the missing contentType
$.ajax({
url: `url`,
contentType: "application/json",
type: "POST",
data: JSON.stringify(data)
});

Categories

Resources