using $http with AngularJS - http

I have the following
angular.module('myApp').factory('dashboard', ['$http', function ($http) {
return {
name: function(str){
return str + ':' + 'works!';
},
getFlags : function(){
$http({ method: 'GET', url: 'http://dalsapent01:8080/DataService/TestDataService.svc/EventTypes', headers: { 'Content-Type': 'application/json; charset=utf-8', 'dataType': 'json' } })
.success(function (data, status, headers, config) {
alert(data);
}).
error(function (data, status, headers, config) {
alert(data);
});
}
}
}])
when I look in fiddler, I see JSON being returned, but status is always 0. any Idea?
Thanks

I think you have a problem in your server response configuration.
Trying your code in this plunker, everything works fine.

Related

In Asp.net, 'Post' Ajax Request Will 'Get'

In my Asp.net Project and in Controller with name 'AjaxController' I have this Action Method:
[HttpPost]
public ActionResult GetList(int year)
{
var res="";
// some codes
return Json(res);
}
And in Js file :
$.ajax({
url: '/Ajax/GetList/',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: 2000,
async: false,
success: function (response) {
// some codes
},
error: function (xhr, status, error) {
alert(error);
},
});
I expect that this method ONLY called with 'POST' but when I check My logs I will see some errors like:
AbsoluteUri :https://example.com/Ajax/GetList/
* Message :A public action method 'GetList' was not found on controller 'Controllers.AjaxController'.
That shows Called as 'GET', NOT 'POST'.
What and where is problem?
Thancks In Advanced
Couple of suggestions from my end -
Remove contentType and async attributes unless really required
Pass JSON object to 'data'
Also, use debugger and breakpoints generously to figure out yourself where your code is going astray
$.ajax({
url: '/Ajax/GetList/',
type: "POST",
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {year: 2000},
//async: false,
success: function (response) {
debugger;
// some codes
},
error: function (xhr, status, error) {
debugger;
alert(error);
},
});

callback in $http({method: 'GET', url: $scope.url})

$scope.fetchQA = function() {
$scope.url = 'js/jsons/QA.json';
$http({method: 'GET', url: $scope.url}).
success(function(data, status, headers, config) {
$scope.QA = data;
});
}
$scope.fetchQA();
function x(){
alert(QA);
}
How do i use function x as a callback for $http.get? or is there any other way to ensure that x() will get executed only after reception of data in fetchQA?
Put it in the callback right after your logic:
$http({method: 'GET', url: $scope.url}).
success(function(data, status, headers, config) {
$scope.QA = data;
x();
});

Asp.net mvc Web-Api Checking checkbox all for Delete all data showing 500 error

I am trying to delete all records with checking all checkboxed values. but it is throwing 500 internal server error.
//delete all menu
function performalldeletemenu()
{
if (confirm('Are you sure you want to delete this menu?'))
{
var AllCheckboxes = new Array();
$("input:checked").each(function () {
//console.log($(this).val()); //works fine
AllCheckboxes .push($(this).val());
});
$.ajax({
type: 'DELETE',
url: '/api/MenuWebApi/DeleteAllMenu/',
data: { deleteservice: AllCheckboxes },
success: function (data) {
if (data.Success == true) {
GetMenuList();
}
},
error: function (xhr, textStatus, errorThrown) {
//window.location = JsErrorAction;
},
dataType: "json",
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
}
Web-Api Method
public HttpResponseMessage DeleteAllMenu(MenuModel objMenuModel)
{
}
please if any have done before please let me know.
1) Ajax request type should be
type: 'Post',
2) You Url should be
url: '/api/MenuWebApi/DeleteAllMenu',

Web Api Parameter always null

Why is the parameter always null when I call the below Post method with the below ajax?
public IEnumerable<string> Post([FromBody]string value)
{
return new string[] { "value1", "value2", value };
}
Here is the call to the Web API method via ajax:
function SearchText() {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/search/",
data: "test",
dataType: "text",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
$.ajax({
url: '/api/search',
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: '=' + encodeURIComponent(request.term),
success: function (data) {
response(data.d);
},
error: function (result) {
alert('Error');
}
});
Basically you can have only one parameter of scalar type which is decorated with the [FromBody] attribute and your request needs to use application/x-www-form-urlencoded and the POST payload should look like this:
=somevalue
Notice that contrary to standard protocols the parameter name is missing. You are sending only the value.
You can read more about how model binding in the Web Api works in this article.
But of course this hacking around is a sick thing. You should use a view model:
public class MyViewModel
{
public string Value { get; set; }
}
and then get rid of the [FromBody] attribute:
public IEnumerable<string> Post(MyViewModel model)
{
return new string[] { "value1", "value2", model.Value };
}
and then use a JSON request:
$.ajax({
url: '/api/search',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ value: request.term }),
success: function (data) {
response(data.d);
},
error: function (result) {
alert('Error');
}
});
You cannot use a simple type for the [FromBody] attribute with the JSON content type. Although the default in Visual Studio has a string from body this is for the application/x-www-form-urlencoded content type.
Put the string value as a property on a basic model class and the deserialiser will work.
public class SimpleModel()
{
public string Value {get;set;}
}
public IEnumerable<string> Post([FromBody]SimpleModel model)
{
return new string[] { "value1", "value2", model.Value };
}
Change the JSON you are sending to:
{"Value":"test"}
whenever we are calling web api action and which take [frombody] parameter then input parameter prefix with =
for example
public string GetActiveEvents([FromBody] string XMLRequestString) {
}
to call above web api action
URI
2.
User-Agent: Fiddler
Content-Type: application/x-www-form-urlencoded
Host: localhost:54702
Content-Length: 936
request body is =data
I hope this will give clear idea.
I've just had a beast of a time with this and .NET Core Web API. So hopefully to save time for someone: The actual problem for me was simple - I wasn't converting to the correct type (Notice #Darins answer uses a VM rather than a string).
The default type in the template is string. I thought because we're sending stringified JSON, we would see a JSON string, but this was not the case. I had to make it the correct type.
E.g. This failed
[EnableCors("AllowAll")]
[HttpPost]
public HttpResponseMessage Post([FromBody]string value)
{
// Do something with the blog here....
var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
return msg;
}
But this worked.
[EnableCors("AllowAll")]
[HttpPost]
public HttpResponseMessage Post([FromBody]Blog value)
{
// Do something with the blog here....
var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
return msg;
}
Ajax Call
function HandleClick() {
// Warning - ID's should be hidden in a real application
// - or have covering GUIDs.
var entityData = {
"blogId": 2,
"url": "http://myblog.com/blog1",
"posts": [
{
"postId": 3,
"title": "Post 1-1",
"content": "This is post 1 for blog 1",
"blogId": 2
},
{
"postId": 4,
"title": "Post 1-2",
"content": "This is post 2 for blog 1",
"blogId": 2
}
]
};
$.ajax({
type: "POST",
url: "http://localhost:64633/api/blogs",
async: true,
cache: false,
crossDomain: true,
data: JSON.stringify(entityData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (responseData, textStatus, jqXHR) {
var value = responseData;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
}

X-editable with .Net and c# web methods

I am using X-Editable Plugin in Asp.net.
I have tried this: Usage with .Net and C# Webmethods
But it gives me error. It is not calling the WebMethod as it should be.
How to solve this problem?
Please help.
Javascript:
$('#username').editable({
url: function (params) {
return $.ajax({
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
HTML:
superuser
WebMethod in Default.aspx:
[System.Web.Services.WebMethod]
public static String TestMethod(String params)
{
//access params here
}
If you want to call a page method, first of all you need to make a request of type POST (also having content-type set will not do any harm):
$('#username').editable({
url: function (params) {
return $.ajax({
type: 'POST',
url: 'Default.aspx/TestMethod',
data: JSON.stringify(params),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
timeout: 10000,
success: function (response) {
alert("Success");
},
error: function () {
alert("Error in Ajax");
}
});
}
});
Also the JSON will be auto deserialized on server side, so you should expect the name, pk and value parameters on server side (this is what plugin is sending according to docs)
[System.Web.Services.WebMethod]
public static String TestMethod(string name, string pk, string value)
{
//access params here
}
In your case the pk will be null as you haven't set one.

Resources