when json is sent from the VB.net it sends it as text. When I inspect the data parameter in the ajax success I see data = [{'PageInformation':'test'}]
But in the following I get invalid character error --WHY?
var dataObj = jQuery.parseJSON(data);
Use double quotes: data = [{"PageInformation":"test"}]
Related
My api sends back a JSON response like this using PHP Silex:
{"response":true,"message":"Bla","userId":"AAA"}
But i can't parse it in my Typescript frontend
this.authService.login(body).then((result : any) => {
console.log(result.data); // => {"response":true,"message":"Bla","userId":"AAA"}
let parsed = JSON.parse(result.data);
console.log(parsed.message); // => throws "SyntaxError: Unexpected token in JSON at position 0\n at JSON.parse (<anonymous>)
My php endpoint using PHP and Silex Framework:
$app->post('/user/login', function (Request $request) use ($app, $config) {
$email = $request->request->get('user-email');
$password = $request->request->get('user-password');
$rsp = loginUser($email,$password);
return $app->json($rsp);
});
When try and hardcode the json object into code, it does parse!
UPDATE SOLUTION
I had to use trim() for result.data to remove whitespaces, somehome the response came with whitespaces and JSON didn't like that. Thank you all for your help.
SOLUTION
i used result.data.trim() for it to work, somehow the response had whitespaces and JSON didn't like that.
You may have a \u0000 char somewhere coming from your PHP code.
Try to remove these characters from your JSON string as soon as you get it from PHP:
this.authService.login(body).then((result : any) => {
string = result.data.replace("\u0000", "");
string = string.replace("\\u0000", "");
let parsed = JSON.parse(string);
i have JSON response which is having backslashes and some responses are not containing the backslashes.
I need to show error message based on the response, How do i parse the JSON response using javascript?
JSON response with out backslashes,
{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}
response with backslashes,
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"}
i tried in the following way but it is working only for JSON response which is not having the backslashes.
var strj = JSON.stringify(err._body);
var errorobjs = strj.replace(/\\/g, "");
Actually the problem is not with / slashs. The JSON is INVALID.
remove these " from backend server
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal
Server
Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal
Server Error"}
double quote before "{"timestamp and one after login"}"
these two highlighted and your code will work.
var data = '{"_body":{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"},"status":500,"ok":false,"statusText":"Internal Server Error"}';
var json_data = JSON.parse(data);
console.log(json_data);
You are actually wrapping body object in string at backend which is not valid.
"body" : "bodyOBJ" //Invalid
"body" : bodyObj //Valid
var obj = JSON.parse(response)
if(typeof obj._body == "string") {
obj._body = JSON.parse(obj._body)
}
console.log(obj);
Solution:
var response = {"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"};
var body = JSON.parse(response._body);
console.log(body.error);
Explanation:
You have a top level object with one key, _body. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. Unless you are able to fix the server side code, you have to decode the nested JSON manually.
I need help guys.
I am trying to fetch data from the server which is returning JSON data but I am getting the following error message (in Chrome 52).
It seems like the JSON data that is returned is invalid or its not in the expected format.
ncaught SyntaxError: Unexpected token <
My server is returning data in the following JSON format
"[{\"ActionCardId\":1,\"ActionCardNumber\":\"279877\",\"AccountNo\":\"2202322179\",\"ClientName\":null,\"CellNumber\":\"0787596971\",\"TenantName\":null,\"TenantCellNumber\":null,\"AddressStandNo\":null,\"AddressStreet\":\"43 DELMAS AVENUE\",\"AddressSuburb\":\"BOKSBURG\",\"AddressCity\":null,\"AddressPortion\":null,\"AddressEarthNo\":null,\"AddressPremise\":null,\"AddressGISKEY\":null,\"AmountDueTotal\":4080.0,\"AmountDue30Day\":null,\"AmountDueCurrent\":null,\"AmountDue60Day\":null,\"ServiceLevy\":null,\"MeterNumberWater\":null,\"MeterNumberElectricity\":\"M22541\",\"MeterNumberElectricity2\":null,\"MeterNumberElectricity3\":null,\"MeterNumberPrePaid\":null,\"IsPrinted\":true,\"IsResidential\":null,\"ActionSuccessful\":false,\"ActionCardDate\":\"2016-08-20T00:00:00\",\"Remarks\":null,\"UnSuccessfulReason\":null,\"CaptureContractorId\":null,\"AddressCombo\":\", 43 DELMAS AVENUE, BOKSBURG, , \",\"BillCycleName\":\"120\",\"ServiceIndicator\":null,\"WaterReading\":null,\"WaterReadingDate\":null,\"ElectricityReading\":null,\"ElectricityReadingDate\":null,\"Unit\":null,\"ActionCardTypeId\":2,\"ContractorId\":1,\"ActionCardStatusId\":1,\"UnSuccessfulActionReasonId\":null,\"TechnicianId\":1,\"AccountInfoId\":null,\"ServiceDeliveryCentreId\":4,\"BillCycleId\":2,\"ActionCardType\":{\"ActionCardTypeId\":2,\"Active\":null,\"CreatedByOnlineUserId\":null,\"DateCreated\":null,\"DateModified\":null,\"Deleted\":null,\"Description\":\"Electricity Disconnection\",\"ModifiedByOnlineUserId\":null,\"Name\":\"ED\",\"CreatedByUser\":null,\"ModifiedByUser\":null},\"Contractor\":null,\"ActionCardStatus\":null,\"UnSuccessfulActionReason\":null,\"Technician\":null,\"AccountInfo\":null,\"ServiceDeliveryCentre\":null,\"BillCycle\":null,\"ActionName\":\"ED\",\"DateCreated\":\"2016-07-06T00:00:00\",\"DateModified\":\"2016-08-13T10:24:17.5833635\",\"CreatedByOnlineUserId\":null,\"ModifiedByOnlineUserId\":\"fa93e65d-e4a7-4a0c-91c6-4561e2612f9c\",\"CreatedByUser\":null,\"ModifiedByUser\":null}]"
I am using Javascript in my client side
$("#importDailyJobs").click(function () {
var technicianId = 1;
var serverUrl = "http://localhost:35825/Mobile/ImportDailyReadings"
$.get(serverUrl, { TechnicianId: technicianId }, function (data, status) {
alert("Success");
console.log(data);
}, "jsonp");
});
I using jsonp because I am using cross domain to get the data.
Your returned data is not a JSON. It's a string. You explicitly expect JSON via the jsonp argument, and you return a string, hence the error.
It seems like you are encountering an error on that URL and the response is enclosed inside an html tag <>.
As suggested by "Jason P" you should check the actual response in the "raw" format. If you are on Google Chrome, you can press F12, then navigate to "Network" Tab, and then select "XHR" after which you should trigger the respective event by clicking on #importDailyJobs. You should see the Ajax Request, on clicking of which you shall be able to view the details for that request, like Headers, Preview, Response etc.
You can view the raw data inside the Response tab.
Also on a side note, just wrap the string in single quotes when you have double quotes inside it, and if you have both then wrap the string in the one which is least used, to prevent lots of escaping as can be seen in your sample response.
I am trying to send a message using the XmppClient.js of kaazing, but I get an : SyntaxError: JSON.parse: unexpected character. The code in javascript is :
var client = new XmppClient(...);
var txtClient = new XmppRoom(...);
sendFromEditor : function(char){
var json = JSON.stringify(char);
//alert(json);
txtClient.sendMessage(json);
};
and I am receiving messages :
txtClient.onmessage = function(msg) {
var data = JSON.parse(msg.body);
alert(data);
The problem is in JSON.parse. The messages I am trying to send are very small (one char).
I also tried to change the maximum message size of kaazing gateway just in case but with no lack!
Any ideas?
Thanks in advance.
I could suggest to surround it with a try catch to check the exact error.. not sure if that helps ;)
I have an ajaxpost that returns a response in form of json and I want to show the message
{ "TEXT" : "Please fix it. there might be otehr reason, and need to address it, or call, incorrect username/password-username/port?. " }
How can I get the value of json? I used the following but Message is undefined, What are the other ways of getting json object
var TEXT = text.resp;
Include this library and below code to parse your json
var json = $.parseJSON(obj.responseText);
var msg = json.message;
You can also try below code
var json = JSON.parse(obj.responseText);
var msg = json.message;
You should try to parse the object and then access it with json["object"] instead of the dot.