Bad format in JSON response AJAX - javascript

I have the follow code, it's call a web service in other PC server.
Data parameters are ok.
"{ ControlId: 'ZAsociated_26037', TaskId: 1495613, UserId: 166396, TBodyId: ''}"
$.ajax({
type: "POST",
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ ControlId: '" + controlId + "', TaskId: " + taskid + ", UserId: " +
userId + ", TBodyId: '" + $(tbody).attr("id") + "'}",
url: getWSPath() + "/GetZAsociatedResults", // CARGAR AQUI LA DIRECCION DEL WEBSERIVCE
success: function (data) {
if (data != null && data.d != "[]") loadAsociatedTable(controlId, data.d);
$("#loadingImg" + controlId).remove();
},
error: function (xhr, ajaxOptions, thrownError) {
$("#loadingImg" + controlId).remove();
alert("Error al obtener los datos: " +thrownError + "\nCodigo de error: " +xhr.status);
}
});
The error is, that when i have the data.d result of WS, JSON add adicionals "\" chars in string:
The begin of response:
[{\"Nombre del Documento\":\"Indemnizacion/Factura. 22076 - Proveedor - Sin: 38653 Global: No\",\"Estado\":\"Pago finalizado\",
I try to replace "\" to null string but it doesnt work
This AJAX when success call to loadAsociatedTable function and this do:
for (var i = 0; i < $.parseJSON(data).length;i++){
and have an error in $.parseJSON(data).length because don't converter this string to object.
I checked in Chrome and the JSON is ok, without this bar "\", and recognize that like a object, the problem is in IE v.11 only.

Can you Post the complete JSON which will help me to analyze
In meanwhile try this
Using Eval on data.d like eval("{"+data.d+"}");
or JSON.Parse(data.d)
try validate you json here http://jsonlint.com/

The server's JSON response is invalid. Some server programmer has misunderstood JSON double quote escaping and tried to apply it everywhere. Have the server return valid JSON. Most server environments have standard JSON libraries which will construct JSON which is not invalid. The correct JSON is of course just
[{"Nombre del Documento":"Indemnizacion/Factura. 22076 - Proveedor - Sin: 38653 Global: No","Estado":"Pago finalizado", ...
You can try to fix the JSON yourself, by replacing \" with ", which would just be
replace(/\\"/g, '"')
but the problem is that you will also destroy \" sequences representing double quote marks inside string values. That's quite a tricky problem to solve. So the best solution is to get the server to send down correct JSON to start with.

Finally I could solve the problem, I used JSON.parse() instead $.parseJSON(), maybe is JQuery version. AJAX response contains this additionals "\" but when I parse this object, JS convert it without problems.
Thanks for your help!

Related

imitating firebug Net tab

In Firebug net tab, in Response\Json tabs, I can see the value returned from CGI, using ajax:
I want to verify the exact characters values, so I can translate it into readable characters (and in the next step, store my values in the same encoding.)
How can I get this value in Javascript?
I tried to use encodeURI() on the ajax returned response, but I only got some [%EF%BF%BD] (the black-diamond-question-mark)
my JS code:
var jqxhr = $.ajax({
type: "GET",
url: AJAX_CGI_URL,
dataType : 'json',
cache: false,
data: { name: AJAX_PARAMS }
})
. . .
case "P_D":
for(var j = 0; j < varVal.length; j++) {
jj=j+1;
updateWidget("d" + jj, varVal[j]);
var res = encodeURI(varVal[j]);
console.log(jj + ": " + res);
} break;
=>
console log:
GET http://.../cgi-bin/xjgetvar.cgi ...
1: %EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%20%EF%BF%BD%EF%BF%BD%EF%BF%BD
which is actually => %EF%BF%BD %EF%BF%BD %EF%BF%BD %EF%BF%BD %20 %EF%BF%BD %EF%BF%BD %EF%BF%BD
[relates to my previous question - JavaScript encodes Hebrew string
I thought it will be easy to get the values Firebug shows. but it is not trivial :( ]
so my question now is - How can I get the same values Firebug gets ?!

Escape special characters in javascript

$.ajax({
url: "/Search/GetMatchCount?idx=" + idx + "&q=" + escape(q) + "&filter=" + escape(filter) + "&fields=" + fields,
success: function (data) {
$("#tabprograms").html("Customer Programs (" + data + ")");
}
});
I have a string "civic+governance" in my search text-box.
I want to retrieve the value of the text-box in some local variable with jquery/javascript. My code is,
var q = document.getElementById('q').value;
The value that I get for q is "civic governance".
The '+' sign seems to be encoded with " ".
How do I not make it encoded to " " and have my string as it is , i.e. "civic+governance".
Your problem is that you are using ESCAPE(q). ESCAPE can not encode the + character you need to use the encodeURIComponent(q) then decode in php with rawurldecode() or you could also change your method to POST.

JSON.parse error in jquery

I am retrieving values from server side code and here is my value ..
["INCOMING",09:09:49,"INETCALL",00:14:09,"ISD",00:05:50,"LOCAL",02:38:02,"STD",01:39:28]
Now as per my need i want to parse it into JSON but on parsing it is giving error..
SyntaxError: JSON.parse: expected ',' or ']' after array element
var dbdata=JSON.parse(data);
and here is my code to get value from server side and parse it into json..
$.ajax({
type: 'GET',
url: 'getdataduration',
async:false,
dataType: "text",
success: function(data) {
var dbdata=JSON.parse(data);
for(var i=0,len=dbdata.length;i<len;i++){
$.isNumeric(dbdata[i]) ? callduration.push(dbdata[i]) : toc.push(dbdata[i]);
}
}
});
Please guys help me.
Thanks in advance..
The value from your server isn't JSON fromat, it's array!
The JSON format reference:https://developer.mozilla.org/en-US/docs/JSON
I think you should generate the data from your server like this:
[{"INCOMING":"09:09:49","INETCALL":"00:14:09","ISD":"00:05:50","LOCAL":"02:38:02","STD":"01:39:28"}]
The value is not valid JSON nor is it valid JS. Every second elemt is invalid
E.g 09:09:49 is not valid it should (probably) be "09:09:49"
The below is a valid array and can be parsed with JSON.parse
["INCOMING","09:09:49","INETCALL","00:14:09","ISD","00:05:50","LOCAL","02:38:02","STD","01:39:28"]
an easy way to test these kinds of issues is to dump the server reply into the browser development console and see what errors if any that produce
change your data to below format
["INCOMING","09:09:49","INETCALL","00:14:09","ISD","00:05:50","LOCAL","02:38:02","STD","01:39:28"]
You can test easily the validty of a JSON with this web tool:
http://jsonlint.com/
Parse error on line 2:
... "INCOMING", 09: 09: 49, "INE
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
As bipen says, if you use PHP, send your data using json_encode(); and put json as datatype in your $.ajax
Correct JSON Data:
// you should create your json like this
var data = '[{
"INCOMING" : "09: 09: 49",
"INETCALL" : "00: 14: 09",
"ISD" : "00: 05: 50",
"LOCAL" : "02: 38: 02",
"STD" : "01: 39: 28"
}
]';
Correct Ajax use with JSON:
// use 'type: post' and 'dataType: json'. Because, post is safe and
you are dealing with json data so it must be dataType: json
$.ajax({
type : 'POST',
url : 'getdataduration',
async : false,
dataType : "JSON",
success : function (data) {
var dbdata = JSON.parse(data);
for (var i = 0, len = dbdata.length; i < len; i++) {
$.isNumeric(dbdata[i].YOUR_JSON_KEY)
? callduration.push(dbdata[i].YOUR_JSON_KEY)
: toc.push(dbdata[i].YOUR_JSON_KEY);
}
}
});
Conclusion:
You are using '$.isNumeric(dbdata[i])' but, as your json data your
first value is string. So it's not gonna to work.

Returned JSON in Orientdb Using Function

I tried to execute this code using functions at OrientDB Studio.
commandResult = db.executeCommand('insert into user (facebookId,instagramId) values ("' + facebookId +'","'+ instagramId +'");
if( commandResult.length == 0){
response.send(200, "ok", "application/json","{\"success\":\"false\"}");
} else {
response.send(200, "ok", "application/json","{\"success\":\"true\", \"#rid\" : \"" + commandResult + "\"}");
}
and then it returns like this
{"success":"true", "#rid" : "user#11:15{facebookId:df,instagramId:sdf} v1"}
My problem now is i want only to return only the rid value. But the problem is in my second key "user#11:15{facebookId:df,instagramId:sdf} v1". I don't know how am I going to parse it since the #rid is in the outside of the curly brace.
Hope from your positive response.
Thanks.
You're concatenating strings. Use the .toJSON() instead:
response.send(200, "ok", "application/json",
"{ \"success\":\"true\", \"#rid\" : \"" +
commandResult.toJSON() + "\"}");

Split items separated by commas (,) in Javascript

My Javascript var contains a 2D array.
If I pop an alert on the the var i get the JSON serialized result, something like:
ID0, DESCRIPTION
I'd like to get each items separated by the , in the value option of the dropdownlist and the other item in the description.
Here's my Javascript code, it would work if split was working correctly but this pops an error because the var doesn't contain a pure string type.
$.ajax(
{
type: "POST",
url: "Projet.aspx/GetDir",
data: "{VP:'" + dd_effort_vp + "',DP:'" + dd_effort_dp + "',Direction:'" + dd_effort_d + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var cars = response.d;
$.each(cars, function(index, value) {
$('#<%= dd_effort_directionp.clientid()%>').append(
$('<option</option>').val(value[value.split(",",0)]).html(value.split(",",1))
}
}
});
I know split doesn't work that way here because of the return value is not a string but you get the result i'd like to achieve, get the first value before the comma has the VALUE of the Dropdownlist and the item after the comma as the HTML text.
Thanks ALOT!
How about value.split(",")[0] instead of value.split(",",0)?
Have you tried value.toString().split(",")?

Categories

Resources