get json string from ajax response text - ajax

The response text of my Ajax request is this :
"<json>
<![CDATA[
{"status":true,"filterMap":{ "summary":"Summary","total":"Total","myProfileMsg":"Opening my profile, please wait","cgBase":"CG Base","export1":"Export"}}
]]>
<offsetinTime>19800000</offsetinTime></json>"
I want to extract just the json string from this.. ie. what i want is :
{"status":true,"filterMap":{ "summary":"Summary","total":"Total","myProfileMsg":"Opening my profile, please wait","cgBase":"CG Base","export1":"Export"}}
How do i do this?

Use replace() & split() functions of String to achieve it:
var json ='<json><![CDATA[{"status":true,"filterMap":{"summary":"Summary","total":"Total","myProfileMsg":"Opening my profile, please wait","cgBase":"CG Base","export1":"Export"}}]]><offsetinTime>19800000</offsetinTime></json>';
var extractedJson=json.replace('<json><![CDATA[','').split(']')[0];
document.body.innerHTML=extractedJson;

Related

webapi controller return csv data

I have a webapi controller code looks like:
[HttpPost]
public HttpResponseMessage DownloadForms(FormCriteria criteria)
{
string downloadData = new FormsToCsvHelper(Umbraco, criteria).GetCsv();
return Request.CreateResponse(HttpStatusCode.OK, downloadData);
}
If i look at the data returned in debugger just before sending it back it looks like:
Created Date,IP,Form Name,Email address,Message,Full Name
31/05/2019 10:43:08,127.0.0.1,Contact form - test,test12#hotmail.com,test,Ismail Mayat
If I copy and paste it into file and save as csv it looks fine in excel.
However the data i actually get back looks like:
"Created Date,IP,Form Name,Email address,Message,Full Name\r\n31/05/2019 10:43:08,127.0.0.1,Contact form - test,test12#hotmail.com,test,Ismail Mayat"
The whole record set it wrapped in quote and the line feed is seen as a literal so when opening file in excel its all on one line.
There is a DelegatingHandler that fire but that is for a specific url request so for this request it does not do anything.
Anyone any ideas whats going on?
WebAPI will serialize the value as JSON by default, so that's why your value is enclosed in double quotes.
To get around this, you can use the StringContent class:
return new HttpResponseMessage(statusCode) {
Content = new StringContent(downloadData, Encoding.UTF8, "text/csv")
};

How to include json as a query parameter in Zapier app

I am trying to create a Zapier app to create a new invoice in Zoho.
Has the requirements: Content-Type: application: x-www-form-urlencoded and input JSON string should be passed using JSONString parameter
The following URI is working for me in REST console when I set the Content Type to "application/x-www-form-urlencoded" and method POST.
https://invoice.zoho.com/api/v3/invoices?authtoken=xxxxxx&organization_id=xxxxxx&JSONString={"customer_id":"xxxxxx","line_items":[{"item_id":"xxxxxx"}]}
However my problem is trying to implement this into Zapier. I think I need to use a function like below to convert the JSON into the right format, but I have no idea how to turn this into a query paramater called JSONString.
create_invoice_pre_write: function(bundle) {
var data = JSON.parse(bundle.request.data);
bundle.request.data = $.param(data);
bundle.request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
return bundle.request;
}
Just need a point in the right direction. I'm not sure what to try next.
You can create an Invoice in Zoho Invoice through Zapier using the below snippet of code.
You can set the query params in bundle.request.params which you want to send it to ZI for the creation of Invoice.
create_invoice_pre_write: function(bundle)
{
var data = JSON.parse(bundle.request.data);
bundle.request.method = "POST",
bundle.request.url = "https://invoice.zoho.com/api/v3/invoices",
bundle.request.params.authtoken = {authtoken},
bundle.request.params.organization_id = {organization_id},
bundle.request.params.JSONString = data
bundle.request.headers= "'Content-Type':'application/x-www-form-urlencoded'";
return bundle.request;
}
This should be working for you. If you have any doubts do let me know.

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();
...
}

How to pass input json with byte[] in web api postman

{
"From":"donotreply#xxx.com", "To":["abc#xxx.com"],
"Cc":["abc#xxx.com"], "Bcc":["abc#xxx.com"],
"Subject":"Export", "TemplateName":"Agent",
"EmailType":"Agent", "Attachments":[{
"Name":"wifi.txt", "Type":"txt",
"StreamData":{"NzI5OTk4NzgxNg0KDQoxIG0tNjczDQoNCjJtLTExMjINCjRtLTE1NzENCjgtMjE4Mw0KDQoxMDYxDQoNCjUwMCBtb2RlbSByZWZ1bmRhYmxl"}}]` ``
}`input json``
I'm calling one method by passing this value as input json using postman, but the StreamDate value alone coming as null.
Can someone please help me on this?
Well it's an invalid JSON object.
StreamData has to be either a string or an object with a key.
Try
{
"From":"donotreply#xxx.com",
"To":["abc#xxx.com"],
"Cc":["abc#xxx.com"],
"Bcc":["abc#xxx.com"],
"Subject":"Export",
"TemplateName":"Agent",
"EmailType":"Agent",
"Attachments":[{
"Name":"wifi.txt",
"Type":"txt",
"StreamData": "NzI5OTk4NzgxNg0KDQoxIG0tNjczDQoNCjJtLTExMjINCjRtLTE1NzENCjgtMjE4Mw0KDQoxMDYxDQoNCjUwMCBtb2RlbSByZWZ1bmRhYmxl"
}]
}
In the sending code Base64 encode the byte array into a string.

JSON.parse is not working

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);

Resources