I get a 400 Bad Request error when I try to call WCF service from client side using ajax. Following is my code,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
Any insights would be really helpfull...
The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error.
Are you making a cross domain request. From the example it looks like you are not. Could you remove
crossDomain: true,
line and try the jquery again.
There are other options also which unnecessay like processdata. Suggest you to use the following code and see if it works or not.
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. When sending JSON, the content type should be 'application/json; charset=utf-8' except that WCF does not like that. I got the same error messages and when I removed the content type I stopped getting this error. By the way, I noticed that you set crossDomain to true, this other question is relevant to that option.
Related
I want to make a request have both JSON and file
My controller :
#Authorize(roles={UserType.ADMIN,UserType.SCHOOL_ADMIN})
#RequestMapping(value="import",method=RequestMethod.POST)
public List<AddUserResponse>importUserBundle(#RequestBody AddUserRequest test,#RequestParam(value="userCsv")MultipartFile[] userCsv)
And got error when making a request :
Content type
'multipart/form-data;boundary=----WebKitFormBoundary62tvsTfonhCQ6HSl;charset=UTF-8'
not supported
Is there any way to make a request with both multipart/form-data and application/json media type?
Your AJAX call should be like this:
$.ajax({
url: '/importUserBundle',
type: 'POST',
data: {
userCsv: FileToSend,
test: JsonData
},
dataType: 'json',
processData: false,
contentType: false,
success: function(data)
{
}
});
EDITED
processData:false Don't process the files
contentType:false Set content type to false as jQuery will tell
the server its a query string request.
Look at this for more info http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
Hope this will help
Please some one help me.
my problem is that when i call the .net webservice using ajax windows phone 8(phonegap app), i get error "object reference not set to an instance of an object" in POST method json formate send in data.
on server side json was receved all values as null.
my ajax is
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(jqXHR.getAllResponseHeaders()+"ajax.responseText==>" + jqXHR.responseText);
},
error: function (xhr) {
console.log(xhr.responseText+"<==ajax.getAllResponseHeaders==>"+xhr.getAllResponseHeaders());
}
});
do not stringify data before sending
I am using JQuery Ajax method and Ajax to talk to a ASP.NET web service.
I have such a setup in my javascript app.
var parameters='Token="'+psToken+'"&ID="'+psDID+'";
$.ajax({
type: "GET",
url: webMethod,
data: parameters,
dataType: "jsonp",
success: function(msg) {
XXXXX.XX(msg.X);
},
As per the IIS log, I can see that all Encoding is happening right and all instances of double quotes get a %22.
The problem is that when for example psToken contains a double quote i.e " , then the web service crashes and I get a 500 error. It doesnt even get to the point of hitting the web methods, hence I cant debug and figure out the error.
What could I be doing wrong.
If the using of jsonp data type is not critical for you, use json dataType with following code:
var parameters = {
'Token': psToken,
'ID': psDID
};
$.ajax({
type: "GET",
url: webMethod,
data: JSON.stringify(parameters),
dataType: "json",
success: function(msg) {
XXXXX.XX(msg.X);
},
I wanted to invoke a .net webservice which is hosted locally on my machine from jQuery .ajax().
the script is included in the static .html file.
the success function is triggered but the response data is NULL.
$.ajax({
type: "GET",
data: '{continent: "' + $('#txtContinent').val() + '"}',
url: "http://localhost:60931/Service1.asmx/GetCountries",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response);
},
failure: function(msg) {
$('#result').empty().append(msg);
}
});
When i alert the response its giving me NULL,
can anyone tell me where im goin wrong, Thanks in advance.
Its because you might be calling the ajax from a static page which is not in http://localhost:60931/. You can put the static html in the localhost and try to run it via the same url. Or you can debug your ajax call by adding
error : function(xhr,status,error){
alert(status);
},
This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.