This question already has an answer here:
Calling Web Api POST always receives null value from jQuery
(1 answer)
Closed 3 years ago.
I have a web api with the following POST Method
public HttpResponseMessage Post([FromBody]string package)
I have a console app that uses the HttpCLient with no problems. When I try to make a call by means of jQuery, I get null on the package variable.
This is the code I have right now:
$.ajax({
url: 'http://localhost:8081/api/Package/',
type: 'POST',
data: JSON.stringify(message),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert(data.length);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: '+xhr.status+', Error Thrown: '+thrownError);
}
});
The "message" variable is a complex model containing two properties.
What could I be doing wrong?
I'll appreciate your help...
There might be an issue with binding the value to the response sent to the server
try sending the data as
$.ajax({
url: 'http://localhost:8081/api/Package/',
type: 'POST',
data: { package : JSON.stringify(message) }
datatype: 'json',
success: function (data) {
alert(data.length);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Status: '+xhr.status+', Error Thrown: '+thrownError);
}
});
I am assuming that your JSON.stringify(message) returns a string value
updated
public HttpResponseMessage Post([ModelBinder]string package)
allowing package to bind from everywhere instead of just body did it for me.
Related
The task is to get the value of some field from k2 with an ajax request. I Googled that it seems like a simple task and is solved by referring to the desired method in the controller
$.ajax({
type: "POST",
url: 'index.php?option=com_k2&task=photo',
dataType: 'json',
success: function (json) {
console.log('success '+json);
},
error: function (jqXHR, text, error) {
console.log('error '+text+' '+error);
}
});
in folder components/com_k2/controllers/item.php
i create function - public function photo(){return 1;} http://joxi.ru/a2XxYpJFwxvRV2
when trying to get my "1" :) I get "File Not Found" as soon as I did not try to access the k2 controller, everything is without success.
I have several ajax calls in my application and all of them work. However one of the calls doesn't seem to respond.
function GetList() {
$.ajax({
url: serviceURL + 'GetList',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data: Store[]) { GetListSuccess(data); },
error: function (error: JQueryXHR) {
OnError(error);
}
});
}
GetList is an stored procedure that I have in my Database. When I execute it through the application I get the following error.
XMLHttpRequest: Network Error 0x2eff, Could not complete the operation
due to error 00002eff
I checked the web console and noticed that for this particular call my Type is 'Plain' instead of 'Json'.
I'm developing an Asana app using Ember.js and I've running into some issue when I need to call the API. The oauth2 sign in/sign up is working great and I receive a working token ( tested it using curl)
I understand that I need to use the "Authorization: Bearer" header to auth with the API and this also work great using curl.
Here's my code:
$.ajax({
url: 'https://app.asana.com/api/1.0/users/me',
type: 'GET',
dataType: "json",
complete: function (resp) { console.log(resp) },
error: function (jqXHR, textStatus, errorThrown) { console.log( textStatus )},
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization: Bearer", "my_access_token") }
});
When I execute this code, I get the following error
Uncaught SyntaxError: Unexpected token : me:1
parsererror
it looks like Asana doesn't reply with a properly encoded JSON file?
this the response that can't be parsed (sorry for the poorly formatted JSON)
{"data":{"id":864403617524,"name":"Sylvain","email":"my#email.com","photo":{"image_21x21":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_21x21.png","image_27x27":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_27x27.png","image_36x36":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_36x36.png","image_60x60":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_60x60.png","image_128x128":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_huge.jpeg"},"workspaces":[{"id":498346170860,"name":"Personal Projects"},{"id":3958612780941,"name":"insideFPL"},{"id":5502245946578,"name":"Shipping Pixel"}]}}
Any help is much appreciated.
Cheers,
S
The problem seems to be that you have set the Authorization header incorrectly. The following works for me:
$.ajax(
'https://app.asana.com/api/1.0/users/me',
{
type: 'GET',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer $token")
},
complete: function (resp) {
console.log(resp);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
}
);
Bearer should be at the beginning of the second parameter, and there should be no colon in either string.
I am trying to submit a form with the user's inserted data and get the html back from the page called (update.asp).
How do I get the html response and how do I write it to a div on the page? The response would be "success".
If my page throws a 500 or other type of error, how can I handle that?
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
// how do i catch the response? is this the right place?
},
error: function(data) {
// how do I catch the error code here?
}
});
The response from the server in both cases would be passed to the callback as the data variable in your example. Try using console.log(data) inside of your callbacks to see the result in your developer console.
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('#myForm').serialize(),
success: function(response) {
$("#yourDIV").html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //output, 500
}
});
});
More on this: ajax()
I'm successfully posting to my controller with the following code, however, success is never being hit only error. What am I doing wrong?
JS:
$.ajax({
url: '/Home/Subscribe',
type: 'POST',
dataType: 'json',
data: { email: $('#sube').val() },
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Controller:
[HttpPost]
public JsonResult Subscribe(string email)
{
return Json(new { foo = "bar", baz = "Blech" });
}
In IE, press F12 to open developer tools. Go to Network tab and click on Start Profiler. Send a request to your Subscribe action - in a list below you will see details of sent request and returned status code. Double click on request to see details - you can then see body of your response. If the request failed with a server error, you will see that error in a body of your response.
One wrong thing I see with your code is that you have hardcoded the url:
url: '/Home/Subscribe'
You should never do this. You should always use url helpers when generating urls in an ASP.NET MVC application:
url: '#Url.Action("Subscribe", "Home")'
Also you are saying that the error callback is always hit but you didn't say what you observed in FireBug or Chrome Developer toolbar when you tried to analyze the AJAX request. If you had done this you would have seen the exact cause of failure for the request because you would have seen what request is sent to the server and what response does the server sends back to the client.
The following is my jQuery ajax snippet that works. Your controller looks right. I assume you have verified it is actually getting called by using a breakpoint.
var p = {
email: $('#sube').val()
};
$.ajax({
url: '#Url.Action("Subscribe", "Home")'
type: 'POST',
data: JSON.stringify(p),
dataType: "text json",
contentType: "application/json",
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});