JSON.parse is not working - ajax

I'm having a very strange problem. My JSON.parse does not seem to work. I tried using eval too but that didn't help either. Below is my code:
var responseDoc = xmlHttp.responseText;
document.getElementById("debug1").innerHTML=responseDoc;
var response = JSON.parse(responseDoc);
document.getElementById("debug2").innerHTML=response.category;
My responseDoc looks like this
{"id":null,"category":"dog","price":"4321","name":"new product 123","sku":"1234","success":true}
But response.category is "undefined". Any ideas why this is happening? I've spent hours on it but couldn't figure out. Thanks a lot!
*UPDATE*:
Removed stringify as some people suggested -> still not working.
If I tried the code below, I get "Uncaught SyntaxError: Unexpected token <" from the console:
var response = JSON.parse(xmlHttp.responseText);
*UPDATE 2 *:
Found the problem. It's because my responseDoc is getting an HTML Doc. Not a JSON Object. Not sure why that happens. This is the code where I process ajax request (I'm using jsp):
JSONObject result = new JSONObject();
result.put("success",true);
result.put("id",request.getParameter("id"));
result.put("name", request.getParameter("name"));
result.put("sku",request.getParameter("sku"));
result.put("price",request.getParameter("price"));
result.put("category",request.getParameter("category"));
out.print(result);
out.flush();

You don't need to stringify something that is already a string (xmlHttp.responseText). The stringify method should be used on a javascript object to serialize it into a JSON string. So get rid of this stringification and simply parse the JSON string that you already have (using the JSON.parse method):
var response = JSON.parse(responseDoc);

You don't need to stringify a string :
var response = JSON.parse(responseDoc);

Related

d3.json() won't execute. keeps getting error: 400

I'm creating a dummy JSON value and is trying to show them but the problem is i keep getting this error:
My code snippet is below:
var jsonData = '[{"id":"31370100","machine_name":"GUMACA BRANCH CAM","machine_type":"CAM","operation_start":"05:04:33","operation_end":"09:04:33"}]'
d3.json(jsonData).then((data)=>{
console.log(data);
});
d3.json takes a URL as the parameter. As you have the JSON already, you probably just need JSON.parse(), and there is no need to use d3 in this instance. So your code would look something like:
var jsonData = '[{"id":"31370100","machine_name":"GUMACA BRANCH CAM","machine_type":"CAM","operation_start":"05:04:33","operation_end":"09:04:33"}]'
let data = JSON.parse(jsonData);
console.log(data);

Receiving null parameters from request in JSP file when are being sent

I've a JSP app. It uploads a file, but to do so the user has to authenticate using a name and a password. So my JSP file starts with:
//0.2.- We get the password
String password = (String) request.getParameter("pass"); // -> This returns NULL
//0.3.- We get the "uvus"
String uvus = (String) request.getParameter("uvus"); //-> This also returns NULL
//More code
So I'm trying to know why am I getting null from those variables.
I went to the form I was uploading, and look for the data that was being sent. Using Firefox Debug Tools, I saw:
So in fact, it was being sent.
As additional info, I'm building the request like this:
var pUvus = document.getElementById("uvus").value;
var pPassword = document.getElementById("pass").value;
var file = document.getElementById("userFile");
var formData = new FormData();
formData.append("upload", file.files[0]);
formData.append("uvus", pUvus);
formData.append("pass", pPassword);
xmlhttp.open("POST","uploadFile.jsp",true);
xmlhttp.send(formData);
At last, I would like to say that I can get vars from application object in the same JSP with no errors, and have received in another pair of JSP files vars at request object without more problems, so I think my fault should be in the way I'm building the request in Ajax, but I've no more clue about that...
Anyone can guide me?
Thanks for your help
Update: #rickz asked for how do I get the file and parse the request (what is done after my problem, trying to get the objects from the request scope):
List items;
items = servlet_up.parseRequest(request);
for(int i=0;i<items.size();i++)
{
FileItem item = (FileItem) items.get(i);
if (! item.isFormField())
{
request.getParameter() won't work for a multipart/form-data request.
If you are using org.apache.commons.fileupload then you should be using something like
if(item.isFormField()){
name = item.getFieldName();
...
}

Rest query params in Java

I need to do some queries against my datastore in Java but I can't seem to get the parameters syntax right. I tried like this:
String params = "?Active=1";
String urlString = "https://api.parse.com/1/classes/Cars" + params;
Or as per the document here:
String params = "where={Active:1}";
But both ways generate an exception.
If I don't do the query and simply try to get all the objects with this request string:
String urlString = "https://api.parse.com/1/classes/Cars"
everything works fine. So the problem is definitely the params sequence. So is there a way to do Prase.com rest queries in Java?
EDIT: adding the exception string in response to a request from the first comment:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.parse.com/1/classes/Cars?where={Active:1}
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1838)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
I should also note that when I use the regular http syntax, as in
params = "?Dealer=asdf";
the query comes back with all the objects, as if the parameter wasn't there.
Here are a couple of working examples for the params string:
String params = "where={\"objectId\":\"ldl49l3kd98\"}";
String params = "where={\"CompanyName\":\"BMW\", \"Price\":{\"$gte\":29000,\"$lte\":49000}}";
And if you need non English characters, like I do, encode the param string like this:
params = URLEncoder.encode(params, "UTF-8");

servicestack - caching a service response using redis

I have a servicestack service which when called via the browser (restful) Url ex:http://localhost:1616/myproducts, it works fine.
The service method has RedisCaching enabled. So first time it hits the data repository and caches it for subsequent use.
My problem is when I try calling it from a c# client via Soap12ServiceClient. It returns the below error:
Error in line 1 position 183. Expecting element '<target response>'
from namespace 'http://schemas.datacontract.org/2004/07/<target namespace>'..
Encountered 'Element' with name 'base64Binary',
namespace 'http://schemas.microsoft.com/2003/10/Serialization/'.
Below is my Client code:
var endpointURI = "http://mydevelopmentapi.serverhostingservices.com:1616/";
using (IServiceClient client = new Soap12ServiceClient(endpointURI))
{
var request = new ProductRequest { Param1 = "xy23432"};
client.Send<ProductResponse>(request);
}
It seems that the soapwsdl used is giving the problem, but I appear to have used the defaults as generated by servicestack..
Any help will be much appreciated.
Update
I was able over come this error by changing the cache code at the service end:
Code that returned error at client end:
return RequestContext.ToOptimizedResultUsingCache(this.CacheClient, cacheKey,
() =>
new ProductResponse(){CreateDate = DateTime.UtcNow,
products = new productRepository().Getproducts(request)
});
Code that works now:
var result = this.CacheClient.Get<ProductResponse>(cacheKey);
if (result == null)
{
this.CacheClient.Set<ProductResponse>(cacheKey, productResult);
result = productResult;
}
return result;
But I am still curious to know why the first method (RequestContext.ToOptimizedResultUsingCache) returned error at c# client?
But I am still curious to know why the first method (RequestContext.ToOptimizedResultUsingCache) returned error at c# client?
From what I can tell, the ToOptimizedResultUsingCache is trying to pull a specific format (xml, html, json, etc) out of the cache based on the RequestContext's ResponseContentType (see code here and here). When using the Soap12ServiceClient the ResponseContentType is text/html (not sure if this is correct/intentional within ServiceStack). So what ToOptimizedResultUsingCache is pulling out of the cache is a string of html. The html string is being returned to the Soap12ServiceClient and causing an exception.
By pulling directly out of the cache you are bypassing ToOptimizedResultUsingCache's 'format check' and returning something the Soap12ServiceClient can handle.
** If you are using Redis and creating your key with UrnId.Create method you should see a key like urn:ProductResponse:{yourkey}.html
Thanks for your response paaschpa.
I revisited the code and I was able to fix it. Since your response gave me the direction, I have accepted your answer. Below is my fix.
I moved the return statement from RequestContext to the response DTO.
Code which throws error when used via c# client (code was returning entire requestcontext):
return RequestContext.ToOptimizedResultUsingCache(this.CacheClient, cacheKey,
() =>
new ProductResponse(){CreateDate = DateTime.UtcNow,
products = new productRepository().Getproducts(request)
});
Fixed Code (return moved to response DTO):
RequestContext.ToOptimizedResultUsingCache(this.CacheClient, cacheKey,
() => {
return new ProductResponse(){CreateDate = DateTime.UtcNow,
products = new productRepository().Getproducts(request)
}
});

Can't access a property in a json object returned

I get a response from an ajax request and store request.responseText in a variable called requestData. requestData data contains a json object pass by php using json_encode().
See a couple of log I made bellow.
requestData : {"status":"ok","to":"","html":"<option value=\"Huberdeau\">Huberdeau<\/option><option value=\"Bo\u00eeleau\">Bo\u00eeleau<\/option><option value=\"Br\u00e9beuf\">Br\u00e9beuf<\/option><option value=\"Saint-R\u00e9mi-d'Amherst\">Saint-R\u00e9mi-d'Amherst<\/option><option value=\"Harrington\">Harrington<\/option>","message":"old"}
My probleme is that I can't access the variable status. None of the following calls get the value properly.
requestData[status] : undefined
requestData.status : undefined
requestData['status'] : undefined
requestData[0]['status'] : undefined
And when I tried to dump my variable by a for log it treated it like string.
dump_var :
0:{
1:"
2:s
3:t
4:a
5:t
6:u
7:s
8:"
9::
in jQuery
instead of $.get
use $.getJSON
$.getJSON(url, function(data){
alert(data.someField);
});
then you don't need to do eval !!
I have found the trick in a comment on an other question. I post it here anyway cause it's a bit difficult to notice in the original discussion.
var requestData = request['responseText'];
var jsonData = eval("( " + requestData + ")");

Resources