Trouble retrieving data from Pocket API using jquery.post() - javascript

I'm attempting to retrieve data from my Pocket account using the Pocket API by accessing it with a jQuery post function. I have obtained the consumer key and access token and when I execute the following code I get a parseerror ...but the data shows up in JSON format in Firebug.
var myPost = $.post("https://getpocket.com/v3/get",
{ "consumer_key": "<<consumer key here>>",
"access_token": "<<access token here>>",
"count": "3",
"detailType": "simple"
},function(data) {
return data
},
"jsonp");
myPost.done(function( msg ) {
console.log(myPost)
alert(msg);
});
myPost.fail(function( jqXHR, textStatus ) {
console.log(jqXHR)
alert( "Request failed: " + textStatus );
});
If I change the dataType on the post call from "jsonp" to "json" I don't get the parse error but instead get a generic error (literally just "error") with nothing returned in teh response tab in Firebug.
Attempts to do this call using jQuery.ajax() have also failed, yielding an error 400.
var something = $.ajax({
"accepts": 'application/json',
"type": 'POST',
"url": "https://getpocket.com/v3/get",
"contentType": 'application/json; charset=UTF8',
"data": {"consumer_key": "<<insert consumer key here>>",
"access_token": "<<insert access token here>>",
"count": "3",
"detailType": "simple"},
"dataType": 'json',
"success": ""
});
Seems like I am close using $.post() but how to I clear that error so I can get the actual response data returned?

Related

Draftable.com API giving truncated response when passed a JSON in Google App Script

I am trying to call an API from draftable.com (https://api.draftable.com/v1/comparisons) using Google App Script. The API takes two files and returns a string. I have made the GET and DELETE functions which are working fine, but when I run a POST function I am getting an error at the
UrlFetchApp.fetch("URL",object);
Error: Request failed for https://api.draftable.com/v1/comparisons
returned code 400. Truncated server response: {"left":["This field is
required."],"right":["This field is required."]}
I am passing a JSON like the code below:
function POST() {
var options = {
"method": "POST",
"headers": {
"Content-Type": "multipart/form-data",
"Accept": "application/json",
"Authorization": "Token {iputmytokenhere}",
},
"left": {
"source_url": "https://api.draftable.com/static/test-documents/paper/left.pdf",
"display_name": "old-example.docx",
"file_type": "pdf"
},
"right": {
"source_url": "https://api.draftable.com/static/test-documents/paper/right.pdf",
"display_name": "newer-example.docx",
"file_type": "pdf"
}
};
var result = UrlFetchApp.fetch("https://api.draftable.com/v1/comparisons", options);
var params = JSON.parse(result.getContentText());
Logger.log(params.identifier);
}
}
Can anyone tell me why is the error coming.

Uncaught SyntaxError: Unexpected token : for a valid JSON

I am trying to get a cross-domain JSON data via $.ajax method
$.ajax({
type: "GET",
dataType: 'jsonp',
url: "http://nrb.org.np/exportForexJSON.php?YY=2016&MM=06",
crossDomain : true,
})
.done(function( data ) {
console.log("done");
console.log(data);
})
.fail( function(xhr, textStatus, errorThrown) {
console.log(xhr);
console.log(xhr.responseText);
// alert(xhr.responseText);
// alert(textStatus);
});
The JSON returned by the url is
{
"Conversion": {
"Currency": [{
"Date": "2016-06-23",
"BaseCurrency": "INR",
"TargetCurrency": "NPR",
"BaseValue": "100",
"TargetBuy": "160.00",
"TargetSell": "160.15"
}, {
"Date": "2016-06-23",
"BaseCurrency": "USD",
"TargetCurrency": "NPR",
"BaseValue": "1",
"TargetBuy": "107.76",
"TargetSell": "108.36"
}, {
"Date": "2016-06-23",
"BaseCurrency": "BHD",
"TargetCurrency": "NPR",
"BaseValue": "1",
"TargetBuy": "285.75",
"TargetSell": "N/A"
}]
}
}
I checked if the JSON is valid by using http://jsonlint.com/. The JSON is Okay. I get a console error.
Uncaught SyntaxError: Unexpected token :
The console is pointing to the error in the following screenshot
Try changing dataType to "json"
Responses with javascript content-type are evaluated automatically.
JavaScript JSON parser treats { and } as a block instead of object.
Set correct Content-Type header for the JSON file.
OR save it with .json extension.
Your url has .json extension while header is jsonp
, Try making it same
Not quite sure of POST and JSONP
: Post data to JsonP

Angular $HTTP response SyntaxError: Unexpected token E

Making a simple POST call using Angular $HTTP service:
authService.login = function(username, password){
var credentials = 'username=' + username + '&' + 'password=' + password;
return $http({
method: 'POST',
url: href,
headers: {'accept': acceptValue, 'content-type': contentType},
data: credentials
}).then(onSuccess, onError);
};
Can't get the error status, instead I get SyntaxError: Unexpected token E.
the console first show the status 401 and immediately after the parse error.
wonder what it does under the hood, what is it trying to parse, and why I'm not able to get error.status to work.
The problem could be with how you are serializing your data. Rather than build the string yourself, you might try passing them directly into data as an object:
data: {username: username, password: password}
Angular should serialize the info in the data object by itself.
If that doesn't work, Angular also has a built-in alternative to its default serializer that mimics the one found in jQuery. Docs on it are here. Your request with this method would look something like:
$http({
url: "/auth/login",
method: "POST",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
data: $httpParamSerializerJQLike({
email: email,
password: password
})
})
If you go with this option, don't forget to inject $httpParamSerializerJQLike as a dependency.
It seems that you request is correctly sent and you receive the response.
I made a try with a RESTful service that returns an 401 status code. Here is my JavaScript code:
var href = 'https://contactsapi.apispark.net/v1/contacts/';
var acceptValue = 'application/json';
var contentType = 'application/json';
var credentials = {}; //'something';
function onSuccess(data, status, headers, config) {
}
function onError(data, status, headers, config) {
console.log('data = '+JSON.stringify(response, null, 2));
}
$http({
method: 'POST',
url: href,
headers: {'accept': acceptValue, 'content-type': contentType},
data: credentials
}).then(onSuccess, onError);
The response object contains in my case the following:
{
"data": {
"code": 401,
"contactEmail": null,
"description": "The request requires user authentication",
"homeRef": "/",
"reasonPhrase": "Unauthorized",
"uri": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2"
},
"status": 401,
"config": {
"method": "POST",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://localhost:8182/contacts/",
"headers": {
"accept": "application/json",
"content-type": "application/json"
},
"data": {}
},
"statusText": "Unauthorized"
}
What could help you is to have a look at the response content (headers / payload). For example, if the payload is a JSON one, the value of the Content-Type header. Perhaps there is a gap between the Content-Type of the response and the actual content. For example, you received from plain text content with content type value application/json.
I made a test to simulate such case (XML content with a content type application/json) and I have the following error:
SyntaxError: Unexpected token <
at Object.parse (native)
at vc (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:15:480)
at Zb (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:82:229)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:83:143
at m (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:7:322)
at dd (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:83:125)
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:84:380)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:119:113
at n.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:133:221)
at n.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:130:233)
Angular tries to parse JSON content but since it's malformed, it can't and throws an error.
It seems to be similar to your error. So I think the problem isn't in your Angular application but in the server...
Hope it helps you,
Thierry

Jquery ajax fail when calling rest webservice

I have a set of REST URIs that i can access after authenticating on the server. This service takes a JSON input with the login information and retrieve a JSON output with the session ID.
When using a Rest client, like a chrome extension, everything works.
Now I want to implement it using JS but despite of the failure return, I can not see any details of what is wrong (error messages are blank) and neither could found what I am missing in my code.
$.ajax({
// the URL for the request
url: "https://host002:50000/b1s/v1/Login",
// the data to send (will be converted to a query string)
data: {
UserName: "manager",
Password: "1234",
CompanyDB: "CUS_001"
},
// whether this is a POST or GET request
type: "POST",
// the type of data we expect back
dataType : "json",
// code to run if the request succeeds;
// the response is passed to the function
success: function( json ) {
$( "<h1/>" ).text( json.title ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
},
// code to run if the request fails; the raw request and
// status codes are passed to the function
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! " + xhr.responseText);
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
// code to run regardless of success or failure
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
xhr.responseText is always blank. Status is always error. errorThrown is always blank as well.
I tried also the $post method but got the same behavior.
Your JSON is incorrect. Try using this
data: JSON.stringify({UserName: "manager", Password: "1234", CompanyDB: "CUS_001"});
While navigating from one url to other there is a cross-domain error thing which pops up.
Try doing this.
Call to a function on your same url using ajax and from there use CURL request to your web service url.

How to send data to a web Service Using Winj.xhr

I am new in Winjs coding I have data in a list .
and i want to send that data to my json Web Service .
I have a success to call to web service and i have the response so the web service is
working but the data doesn't seem to be sent. I dont know how to declare the data.
I have many data to sent like(username,first_name,last_name,password) to my Register.json
The Register.json have this response after the execution:
{
"format":
"json",
"success":
false,
"errors":
["User name is empty"],
"result":
null
}
so i m sure that data doesnt be sent
function Register() {
var dataArray = [
{
username: "Marley",
first_name: "dog",
last_name: "ded",
password: "pdre4252d"
}];
WinJS.xhr({
url: "my_Base_URL/Register.json",
type: "post",
headers: { "Content-type": "application /x-www-form-urlencoded" },
data: dataArray
// data:JSON.stringify(dataArray)
}).done(
function complete(result) {
if (result.status === 200) {
console.log("Success: Response Text: " + result.responseText);
}
else {
console.log("Fail:Response Text: " + result.responseText);
}
},
function error(error) {
console.log("error");
},
function progress(result) {
}
);
}
I will be thinkful if someone give me some help.
The WinJS.xhr() is a promise wrapper around XMLHttpRequest, which means it delegates your parameters to an XMLHttpRequest object and returns a WinJS.Promise object. The parameters may not be delegated correctly so play with adding and empty string for a username and such. Otherwise you can mimic the same functionality by creating your own WinJS.Promise with an XMLHttpRequest inside.

Categories

Resources