"400 Bad Request" response for AJAX request - javascript

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).

you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})

JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Related

Uncaught SyntaxError: Unexpected token u with Ajax post

I am stumped as to how to solve/diagnose ajax/jquery error.
This is my function:
var LogIn = {
Email: $("#Name").val(),
MobileNo: $("#txtMobileNumber").val(),
PinCode: '',
Message: '',
Success:false
};
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json",
url: "https://a different server domain/api/LoginRequest",
data: JSON.stringify(LogIn),
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
I get this error:
jQuery doesn't support using POST and jsonp and the reason for that is very simple: when you inject a <script> tag into the DOM (which is what jQuery does when you use jsonp), the browser will send a GET request to the remote endpoint which has been referred to in the src property of this tag.
So basically you will need to use GET instead:
type: "GET"
Also since the data is sent as query string parameters you should remove the content type:
contentType: "application/json",
and do not JSON.stringify the data.
And here's the full example:
$.ajax({
type: "GET",
crossDomain: true,
dataType: 'jsonp',
url: "https://a different server domain/api/LoginRequest",
data: LogIn,
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
Of course this will work only if the remote endpoint supports JSONP and the GET verb.
Personally I would recommend using CORS instead of JSONP as it would give you much more options. You will be able to use POST in this case. Please refer to the following material as it seems you are using ASP.NET Web API on the server and trying to make a cross domain AJAX call: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Cannot do a post with jquery with json in body

With Chrome REST service I do this: a post to a certain url, I send a json string in the body, I set the content type as application/json and when I execute the post I get the proper answer.
I am trying to do the same post with jquery.
I first try with:
var beacon = {"beaconid.minor":2,"beaconid.UUID":"beaconnr","beaconid.major":1};
$.ajax({
type: "post",
data: JSON.stringify(beacon),
contentType: "application/json",
dataType: "jsonp",
crossDomain: true,
url: "myurl"}).done(function() {
alert("success");
}).fail(function()
{
alert("error");
});
by I seem to get no answer, I don't get the success alert nor the error alert.
I have then tried with:
var jqxhr = $.post( "myurl", {"beaconid.minor":2,"beaconid.UUID":"beaconnr","beaconid.major":1}).done(function(data, textStatus, jqXHR)
{
}).fail(function(jqXHR, textStatus, errorThrown)
{
alert(textStatus);
});
At least now I get an alert with the textStatus as an error. It is something...but not enough. I could I do a successful post?
The issue is you're setting dataType: "jsonp" for a POST request. JSONP doesn't support POST requests, only GET requests.
I suggest changing to dataType: "json" to see if the service supports CORS. If it doesn't then you'll have to do something like proxy the request through the local server, to get around CORS.
You should not be sending "post" as "type", rather as "method"
And like pointed above, the data type should be json and not jsonp.
$.ajax({
method: "post",
data: JSON.stringify(beacon),
contentType: "application/json",
dataType: "json",
url: "myurl"}).done(function(response) {
alert("success");
//if in chrome
//console.log(response);
}).fail(function(error)
{
//if using Chrome
//console.log(error);
alert(error);
});

ERROR: bad URI when sending data as JSON with GET method to a Rails resource

Hello I'm performing a GET request on a RESTful Rails resource, like so:
function getGroups(category) {
$.ajax({
type: 'GET',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "category":category }),
success: function(data) {alert(data)},
contentType: "application/json",
dataType: 'json'
});
});
getGroups("own_groups");
The problem is that Webrick server errors out like this:
ERROR bad URI
`/groups.json?{%22access_token%22:%22569669d8df0456%22,%22category%22:%22own_groups%22}'.
It must be something related with how the JSON data is parsed, because I am having no problems with another GET request WITHOUT JSON data, and a POST request WITH JSON data...
Update: adding code for POST request (where JSON.stringify is required)
function addGroup(name, description) {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "group_name":name, "group_description":description}),
success: function(data) { alert("ok")},
contentType: "application/json",
dataType: 'json'
});
};
addGroup("nice group", "full of people");
Do not use JSON.stringify. Simply put:
data: {"access_token":"569669d8df0456", "category":category },
Moreover, you do not need to specify complete url http://localhost:3000/groups.json, it can be just simply groups.json

Facebook Graph jQuery AJAX call to post a photo on user's behalf

I'm trying to post a photo on the users behalf. I've been searching the web for the last 4 hours and I'm out of ideas.
JS:
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})
the error function outputs the following:
[object Object]|error|Bad Request
I think there must be something wrong with the ajax request itself, but I can't figure out what it is. I've reconstructed my request using the Facebook Graph API explorer and everything works fine there. Any ideas?
Need to define the correct data type in the ajax request ( jsonp ), just try this will work :
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
dataType: "jsonp", //Just add this line ( jsonp not json ),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})

AJAX is not sending request

I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});

Categories