Error when making Ajax REST API calls - javascript

I have this application that I am trying to create.
The application should login (using REST API), and respond with a session id.
I have created a button, which calls the JavaScript function that performs the ajax call, which in turn tries to login.
The results are appended to the div (appscan_results)
Here's is the code
<html>
<head>
<title> AppScan Issues Exporter </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function login(){
var request = $.ajax({
type:"POST",
url:"myurl",
dataType: "json",
contentType: "application/json",
data:{
"userId": "username",
"password": "password",
"featureKey": "AppScanEnterpriseUser",
"clientVersion": "",
"clientIp": "",
"clientHostName": ""
},
});
request.done(function (jqXHR){
alert('Success');
$("#appscan_results").html(jqXHR.responseText);
});
request.fail(function(jqXHR) {
alert('Failure');
$("#appscan_results").html(jqXHR.responseText);
});
}
</script>
<button onclick="login()">Get Issues</button>
<div id="appscan_login"></div>
<div id="appscan_results"></div>
</body>
</html>
After it runs, I get the following error:
Exception thrown by application class 'org.apache.wink.server.internal.RequestProcessor.handleRequest:195'
javax.servlet.ServletException: org.codehaus.jackson.JsonParseException: Unexpected character ('u' (code 117)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at [Source: com.ibm.ws.webcontainer.srt.SRTInputStream#d80cceaa; line: 1, column: 2]
at org.apache.wink.server.internal.RequestProcessor.handleRequest(RequestProcessor.java:195)
at com.ibm.websphere.jaxrs.server.IBMRestServlet.service(IBMRestServlet.java:106)
at [internal classes]
at com.ibm.appscan.server.filters.ClickjackFilter.doFilter(Unknown Source)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:192)
at [internal classes]
What am I missing in the code?
PS: I have tested the REST call using REST API client and I do get a response,

org.codehaus.jackson.JsonParseException
Your servlet/rest controller is not able to parse the Input JSON string and convert it to a Valid Java Object.
Change data to
data:JSON.stringify({
userId: "username",
password: "password",
featureKey: "AppScanEnterpriseUser",
clientVersion: "",
clientIp: "",
clientHostName: ""
},
})

Related

Dropbox shared_link

I'm writing code to get a link to an image file in Dropbox. However, I get a 400 error.
The error content was "Error in call to API function " sharing / create_shared_link_with_settings \ ": request body: could not decode input as JSON". I think the description method is wrong, but I don't know what's wrong.
<!doctype html>
<html>
<head>
</head>
<body>
<form id="form">
<h3>ファイルを選択してアップロード</h3>
<input type="file" id="file">
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
var input = document.getElementById("file");
//ダイアログでファイルが選択された時
input.addEventListener("change", function (evt) {
//ドロップボックスのファイルAPI
json = {
"url": 'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings',
"raw_url": "https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings",
"type": 'post',
"data": {
"{\"path\": \"/hand4.jpg\",\"settings\": {\"audience\": \"public\",\"access\": \"viewer\",\"requested_visibility\": \"public\",\"allow_download\": true}}": ""
},
"headers": {
"Authorization": "Bearer *********",
"Content-Type": "application/json"
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.error(data);
}
}
$.ajax(json)
})
</script>
</body>
</html>
The /2/sharing/create_shared_link_with_settings Dropbox API endpoint is an "RPC" style endpoint, meaning it expects its parameters as JSON in the request body.
The error is indicating that you are not sending valid JSON in the request body.
In your code, you're attempting to set that via the data field in your json dict, which is itself a dict with one element, with the key being the escaped string of your desired parameters, and the value being an empty string. That should instead just be the JSON string of the desired parameters.
For example, you probably meant to do something like this instead:
"data": JSON.stringify({"path": "/hand4.jpg","settings": {"audience": "public","access": "viewer","requested_visibility": "public","allow_download": true}}),

U.N. FAO API - How do I do a POST data request via JS with this API?

I am trying to do a POST request (via JavaScript AJAX) to the United Nations Food and Agriculture Organization (U.N. FAO) API to get some data points. While I have successfully completed GET requests to this API with no problem, the POST requests continuously fail. I've done this type of request with many other APIs, but this one I can't figure out.
My code and URLs related to the API are below.
Can anyone please help me successfully complete a POST data request to this FAO API? Either modifying my code or creating your own example code would be fine.
The API endpoint is here:
http://fenixapps2.fao.org/api/v1.0/en/data/
The API's technical description is here:
http://fenixapps2.fao.org/api/v1.0/
The 'Example Page' for the API is here:
http://faostat.github.io/faostat-api/
The 'Showcase Page' for the API is here:
http://fenixapps.fao.org/repository/api/
My code -- a working GET request + non-working POST request -- is below.
You can cut-and-paste it into a text editor and it will work as an HTML file.
<html>
<head>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascript'>
function test() {
// (1) GET requests work fine.
// Based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
$.ajax({
type: 'GET',
url: 'http://fenixapps2.fao.org/api/v1.0/en/classifications/QC',
success: function(response) {
console.log("metadata GET response:");
console.log(response);
}
});
// (2) POST requests do NOT work with my code.
// Originally based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
// Modified per API description at: http://fenixapps2.fao.org/api/v1.0/
$.ajax({
url: "http://fenixapps2.fao.org/api/v1.0/en/data/",
traditional: true,
data: {
"datasource": "production", //test
"output_type": "objects", //arrays
"api_key": "n.a.",
"client_key": "n.a.",
"lang": "en",
//"domain_code":"QC", //domain_code (from example page - http://faostat.github.io/faostat-api/) replaced by domain_codes?
"domain_codes": ["'QC'"],
//"thousand_separator": ",", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
//"decimal_separator": ".", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
"decimal_places": "2",
"List1Codes": ["'33'"],
"List2Codes": ["'2510'"],
"List3Codes": ["'15'"],
"List4Codes": ["'2007'","'2008'","'2009'","'2010'","'2011'","'2012'","'2013'","'2014'"],
"List5Codes": null,
"List6Codes": null,
"List7Codes": null,
"null_values": true,
//"group_by"
//"order_by"
//"operator"
"page_size":"100",
"limit": "10",
"page_number":1
//"show_codes"
//"show_flags"
//"show_unit"
},
type: 'POST',
success: function(response) {
console.log("data POST response:");
console.log(response);
}
});
}
</script>
</head>
<body onload='test();'>
<div id='out'></div>
</body>
---UPDATE---
I have tried changing the data section within $.ajax() so that the url created exactly matches the format of that of the cURL example from the FAO 'Example' page (http://faostat.github.io/faostat-api/). However, this has not altered the API's response. My updated code is included below -- the new console.log(urlPlusData); line I believe should reflect the full url that the code is generating for the POST.
<html>
<head>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascript'>
function test() {
// (1) GET requests work fine.
// Based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
$.ajax({
type: 'GET',
url: 'http://fenixapps2.fao.org/api/v1.0/en/classifications/QC',
success: function(response) {
console.log("metadata GET response:");
console.log(response);
}
});
// (2) POST requests do NOT work with my code.
// Originally based on example by FAOSTAT (http://faostat.github.io/faostat-api/)
// Modified per API description at: http://fenixapps2.fao.org/api/v1.0/
$.ajax({
url: "http://fenixapps2.fao.org/api/v1.0/en/data",
traditional: true,
data: {
"datasource": "production", //test
"output_type": "objects", //arrays
"api_key": "n.a.",
"client_key": "n.a.",
"lang": "en",
//"domain_code":"QC", //domain_code (from example page) replaced by domain_codes?
"domain_codes": ["QC"],
//"thousand_separator": ",", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
//"decimal_separator": ".", //not mentioned at http://fenixapps2.fao.org/api/v1.0/, only on example page.
"decimal_places": "2",
"List1Codes": ["33"],
"List2Codes": ["2510"],
"List3Codes": ["15"],
"List4Codes": ["2007","2008","2009","2010","2011","2012"],
"List5Codes": ["null"],
"List6Codes": ["null"],
"List7Codes": ["null"],
"null_values": true,
//"group_by"
//"order_by"
//"operator"
"page_size":"100",
"limit": "10",
"page_number":"1"
//"show_codes"
//"show_flags"
//"show_unit"
},
beforeSend: function (jqXHR, settings) {
urlPlusData = settings.url + "?" + settings.data;
},
type: 'POST',
success: function(response) {
console.log("data POST response:");
console.log(urlPlusData);
console.log(response);
}
});
}
</script>
</head>
<body onload='test();'>
<div id='out'></div>
</body>

Jquery ajax POST response is null

I want to get the url in this link:
CODE:
<div id="id01"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "http://www.panet.co.il/series/seriesLink/138099",
success: function(info){
document.getElementById("id01").innerHTML = info.data.url ;
}
});
});
</script>
The problem is in the response. When you use JSONP the response result must be wrapped inside a jsonCallback() function:
jsonCallback({"Name": "Foo", "Id": 1234, "Rank": 7});
Look for more information here.
Looks like the returned data can't be parsed correctly. Here's my error message in Google Chrome:
Uncaught SyntaxError: Unexpected token :
The data returned from http://www.panet.co.il/series/seriesLink/138099 has some UTF8 characters in it. Maybe that's the cause.

Uncaught TypeError: Cannot use 'in' operator to search for '' in JSON string

I've use token input in my website, and here's how I initialize the token input:
$(document).ready(function () {
var populateValue = document.getElementById('<%= hiddentokenPrePopulate.ClientID%>').value
$("#<%= tokenEmployee.ClientID%>").tokenInput("../Employee/getEmployeeDetails.ashx", {
deleteText: "X",
theme: "facebook",
preventDuplicates: true,
tokenDelimiter: ";",
minChars: 3,
tokenLimit: 1,
prePopulate: populateValue
});
});
The script was stuck on this line:
prePopulate: populateValue
When I remove this line, there won't be any javascript error, but I need this as I need to pre-populate the token input. The populateValue is:
[{
"id": "11566",
"name": "Smith - White"
}]
There was a javascript error:
Uncaught TypeError: Cannot use 'in' operator to search for '47' in [{"id":"11566","name":"Smith - White"}]`
How can I fix this error?
You need to parse the string in your populateValue variable to an object:
prePopulate: $.parseJSON(populateValue)
Or alternatively, in plain JS:
prePopulate: JSON.parse(populateValue)
You may get this error if you are using a string as an array. Say that if you got a json from an ajax, and you forgot to parse the result, and using the result as an array. The remedy is as above, to parse the json before using it.
Your server side code means .CS page where you have written your WebMethod, should always return .ToList() means array of json
Here is my .CS page code:
WebMethod
public static string PopulateDetails(Guid id){
var prx = new ProductProxy();
var result = prx.GetFirstorDefault(id); // this method is having List<ClassObject> return type
return JsonConvert.SerializeObject(result);
}
Then in my jQuery post method:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Productjq.aspx/PopulateDetails",
data: JSON.stringify({id: id}), // This is Id of selected record, to fetch data
success: function(result) {
var rspns = eval(result.d); // eval is used to get only text from json, because raw json looks like "Id"\"1234"
$.each(rspns, function() {
$('#<%=txtProductName.ClientID %>').val(this.Name);
});
},
error: function(xhr, textStatus, error) {
alert('Error' + error);
}
});
I was getting this error as well.
C# Api returning Serialized Dictionary data.
return JsonConvert.SerializeObject(dic_data);
return new JavaScriptSerializer().Serialize(dic_data);
Kept on getting this error message, until i just returned the Dictionary data directly without trying to Serialize
return dic_data;
No more errors on the browser side. Not sure why.

Call external web service using jquery

I am using the following code to call external web service using jquery. In Chrome, I am getting this '500 Internal Server Error' and in firefox, it shows '0'
I am unable to figure out the problem. Here is my complete code..
<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCall").click(function (event) {
$.ajax({
type: "POST",
url: "www.google.com",
data: "{'ESS123', 'aaaaaa', '', 'abc#hotmail.com', '23424234', '', 0, 100, 1000007, 1, '', 12, '','','', '2013', '', 1, 1000006, 1000033, 100, 1000012, 1000012, 1000001, 1000001, 100, 'caff4eb4fbd6273e37e8a325e19f0991'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('s');
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert('s');
//alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
</script>
<body>
<input type="button" value="Submit" id="btnCall" />
</body>
There could be additional reasons, but your data argument does not contain valid JSON. Invalid input is a common reason for 500 Internal Server Errors.
See JSONLint:
Parse error on line 1:
{ 'ESS123', 'aaaaa
-----^
Expecting 'STRING', '}'
(Hint, strings in JSON must be quoted with " characters, and, unlike arrays, objects require key:value pairs not a list of values).

Categories

Resources