I am building a web app using the Box API, but I'm having trouble simply creating a folder in the root directory. The token is set to a developer token which should be active.
The error I'm receiving now is Bad Request. What is wrong with this code? I'm also having trouble receiving authentication for the user, but I decided to tackle this first.
function createTestFolder() {
$.ajax('https://api.box.com/2.0/folders',
{
data: { name: 'CreatedFolderFromjQuery', parent: { id: '0' } },
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + window.token);
},
contentType: 'json',
success: function(data, status, xhr) {
alert(status);
},
error: function(xhr, status, error) { alert(error); }
});
}
EDIT : When I change the URL to https://box.com/api/1.0/folders, I seem to get a successful response. That is, the success function gets called, rather than the error function. However, the folder is still not uploaded to my account.
EDIT 2 : Using the curl command line and following the API documentation, I still receive the same error message. Here are the details:
{"type":"error", "status":400, "code":"bad_request", "context_info":{"errors":[{"reason":"invalid_parameter", "name":"entity_body", "message":"Invalid value ''{name:New Folder,'. Entity body should be a correctly nested resource attribute name/value pair"}]}, "help_url":"http://developers.box.com/docs/#errors", "message":"Bad Request", "request_id":"128521198353f4fc831c7e6"}
curl: (6) Could not resolve host: parent
curl: (3) [globbing] unmatched brace in column 1
curl: (3) [globbing] unmatched close brace/bracket in column 2
Ah, I have solved my own question. I am not familiar with jQuery, and here was my mistake:
data: { name: 'CreatedFolderFromjQuery', parent: { id: '0' } },
With jQuery's AJAX API, data needs to be a string. I needed to serialize my POST data into JSON:
data: JSON.stringify({ name: 'CreatedFolderFromjQuery', parent: { id: '0' } }),
Once I realized this, and added the JSON.stringify() the request was sent properly.
Related
I have a very strange issue here, that I think has got something to do with the Backbone.js routing.
In our mobile app, there is a login-screen, that executes a AJAX-Post-Request (with jQuery), that runs against an API. Username, password and a third parameter are in the POST-body. This works like a charm.
The strange behaviour kicks in, after Backbone.js begins to to do some routing. After re-directing the browser, (only!) the username and password are send as a parameter-list to the GET request.
So the request i.e.
http://localhost:3000/#login
for unknown reason becomes
http://localhost:3000/?username=myuser&password=mypassword#login
Please notice, that the new parameters in the GET-request are not 100% part of the POST-body, because the savePassword-parameter is missing. Also notice, that the login-request goes against the API, (/api/user/login), not the route of the login-screen (/#login)
I already tried out a lots of things, also taking all the backbone-sourcecode apart, but still can't find how to prevent this behaviour.
Another notice: I see this only on mobile, so in the UIWebView on iOS and the WebView-object on Android. Maybe this issue is also related to the mobile...
I am very happy for any help, answers or hints, how to disable this behaviour and get the username/password out of this freakin URL.
Edited:
This is the AJAX-Request for loggin in.
login: function(username, password, savePassword, successcallback, errorcallback) {
$.ajax({
method: 'POST',
dataType: 'json',
url: config.api_base_url + 'user/login',
data: {
username: username,
password: password,
savePassword: savePassword
},
success: function(data, response, xhr) {
app.auth_token = xhr.getResponseHeader('Authtoken');
$.cookie('auth_token', app.auth_token);
if (successcallback) {
successcallback();
}
},
error: function(data) {
if (errorcallback) {
errorcallback(data);
}
}
});
}
According to jQuery.ajax() docs:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
And than, you should add in your settings processData equal to false:
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
Code jQuery.ajax():
login: function(username, password, savePassword, successcallback, errorcallback) {
$.ajax({
method: 'POST',
dataType: 'json',
url: config.api_base_url + 'user/login',
data: {
username: username,
password: password,
savePassword: savePassword
},
processData: false,
success: function(data, response, xhr) {
app.auth_token = xhr.getResponseHeader('Authtoken');
$.cookie('auth_token', app.auth_token);
if (successcallback) {
successcallback();
}
},
error: function(data) {
if (errorcallback) {
errorcallback(data);
}
}
});
}
I am trying to send an Ajax POST request using Jquery but I am having 400 bad request error.
Here is my code:
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
},
error: function(e) {
console.log(e);
}
});
It Says: Can not build resource from request.
What am I missing ?
Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object.
So the correct version is here:
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: JSON.stringify({
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}),
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
May be it will help someone else.
In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.
It turned out to be the anti forgery token.
$.ajax({
url: "/Cart/AddProduct/",
data: {
__RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
productId: $(this).data("productcode")
},
The problem was that the .Net controller wasn't set up correctly.
I needed to add the attributes to the controller:
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[DisableCors]
[HttpPost]
public async Task<JsonResult> AddProduct(int productId)
{
The code needs review but for now at least I know what was causing it. 400 error not helpful at all.
Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.
400 Bad Request
Bad Request. Your browser sent a request that this server could not
understand.
Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.
415 Unsupported Media Type
Try this.
var newData = {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
};
var dataJson = JSON.stringify(newData);
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: dataJson,
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.
The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.
You have to get name and value from craft in your template :
<script type="text/javascript">
window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>
and pass them in your request
data: window.csrfTokenName+"="+window.csrfTokenValue
You need to build query from "data" object using the following function
function buildQuery(obj) {
var Result= '';
if(typeof(obj)== 'object') {
jQuery.each(obj, function(key, value) {
Result+= (Result) ? '&' : '';
if(typeof(value)== 'object' && value.length) {
for(var i=0; i<value.length; i++) {
Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
}
} else {
Result+= [key, encodeURIComponent(value)].join('=');
}
});
}
return Result;
}
and then proceed with
var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: buildQuery(data),
error: function(e) {
console.log(e);
}
});
I'm hoping this may be of use to those encountering 400 errors while using AJAX in Wordpress going forward. Even though this question is many years old, the solutions provided have all been programmatic, and I'm sure many have stepped through their code to repeatedly find it's correct, yet continue to find it is not working.
I found dozens of results asking how to resolve "WP AJAX request returning 400 Bad Request" or "WP AJAX request returning 0" and nothing today worked.
Googling "How do I fix 400 bad request on Wordpress?" finally resulted in the answer appearing from https://wp-umbrella.com/troubleshooting/400-bad-request-error-on-wordpress/
Clear your Web Browser Cache and Cookies
You may be surprised, but most 400 errors in WordPress can be fixed by clearing your browser's cache and cookies. Browser caches temporarily store images, scripts, and other parts of websites you visit to speed up your browsing experience.
Clearing both my cache and cookies saw the 400 Bad Request code disappear and results return AJAX results as expected.
I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular
I'm trying to run this generated by facebook code on my site, but it is not working. I'm getting error "SyntaxError: missing } after property list".
Code:
FB.api(
'me/objects/my-app-name-was-here:photo',
'post',
{
og:url: http://samples.ogp.me/MYAPPIDWASHERE,
og:title: Sample Photo,
og:type: my-app-name-was-here:photo,
og:image: https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png,
og:description: ,
fb:app_id: MYAPPIDWASHERE
},
function(response) {
// handle the response
}
);
What is wrong with this code? I got it from here:
https://developers.facebook.com/apps/MY_APP_ID_WAS_HERE/open-graph/object-types/
the API you are trying to use here is
FB.api('/me/feed', 'post', { message: body }, function(response) {})
In your code, the object part(the third argument), is not a valid object, and that's why the error. please provide a valid object here.
And by the way, the link you provided is broken
Thanks
FB.api(
'me/objects/my-app-name-was-here:photo',
'post',
{
url: 'http://samples.ogp.me/MYAPPIDWASHERE',
title: 'Sample Photo',
type: 'my-app-name-was-here:photo',
image: 'https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png',
description:'' ,
app_id: 'MYAPPIDWASHERE'
},
function(response) {
// handle the response
}
);
Facebook api third param should be an object. like {fields: 'value'}
i am leveraging CamFind's API for image recognition in my windows phone 8 app. On their site they have given an example for how to use the API with Node.js.. however i am writing a PhoneGap Windows Phone app and dont have this availble.
I would like to use just plain jquery/javascript to use this API.
Here's the example provided on their site:
var Request = unirest.post("https://camfind.p.mashape.com/image_requests")
.headers({
"X-Mashape-Authorization": "Z**********************"
})
.send({
"image_request[locale]": "en_US",
"image_request[language]": "en",
"image_request[device_id]": "<image_request[device_id]>",
"image_request[latitude]": "35.8714220766008",
"image_request[longitude]": "14.3583203002251",
"image_request[altitude]": "27.912109375",
"focus[x]": "480",
"focus[y]": "640",
"image_request[image]": "/tmp/file.path"
})
.end(function (response) {
console.log(response);
});
Here's how i am trying to do the same using jquery/ 'plain' javascript
$.ajax({
url: 'https://camfind.p.mashape.com/image_requests', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
type: 'POST', // The HTTP Method
data: {
"image_request[locale]": "en_US",
"image_request[language]": "en",
"image_request[device_id]": "<image_request[device_id]>",
"image_request[latitude]": "35.8714220766008",
"image_request[longitude]": "14.3583203002251",
"image_request[altitude]": "27.912109375",
"focus[x]": "480",
"focus[y]": "640",
"image_request[image]": "http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg"
}, // Additional parameters here
datatype: 'json',
success: function(data) { alert(JSON.stringify(data)); },
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "Z**********************");
}
});
Issue/Question:
When i do it through javascript/jquery - it seems to be complaining about missing image_request[image] attribute. It never hits the success block.
Am i doing something wrong in terms of how i transformed the Node.js API request example (1st block of code above) provided by CamFind VS. how i am doing trying to consumer the API through plain through Javascript (2nd block of code above)?
Thanks!!
Fyi, references i am using:
Consume an API in javacstipt: https://www.mashape.com/imagesearcher/camfind#!endpoint-1-Image-Request
CamFind API usage: https://www.mashape.com/imagesearcher/camfind#!endpoint-1-Image-Request
I know this is an old question but having stumbled across it whilst trying to solve it myself I thought I should answer it for the future.
The issue is this line:
"image_request[image]": "http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg"
It should be:
"image_request[remote_image_url]": "http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg"
So the complete code is:
$.ajax({
url: 'https://camfind.p.mashape.com/image_requests', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
type: 'POST', // The HTTP Method
data: {
"image_request[locale]": "en_US",
"image_request[language]": "en",
"image_request[device_id]": "<image_request[device_id]>",
"image_request[latitude]": "35.8714220766008",
"image_request[longitude]": "14.3583203002251",
"image_request[altitude]": "27.912109375",
"focus[x]": "480",
"focus[y]": "640",
"image_request[remote_image_url]": "http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg"
}, // Additional parameters here
datatype: 'json',
success: function(data) { nowDoSomethingFun(data); },
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Key", "YOURKEY")
}
});
}
I am not familiar with this API but you might try formatting your data parameter like this:
data: {
image_request: {
locale: 'en_US',
language: 'en',
device_id: '<image_request[device_id]>',
latitude: '35.8714220766008',
longitude: '14.3583203002251',
altitude: '27.912109375',
image: 'http://exelens.com/blog/wp-content/uploads/2013/03/bmw-car-2013.jpg'
},
focus: {
x: '480',
y: '640'
}
}