Differentiate between HTTP request and Ajax request - javascript

I am currently working on ASP.NET WebApi and Angularjs
WebApi have a method
[System.Web.Http.AcceptVerbs("POST")]
[System.Web.Http.HttpPost]
public HttpResponseMessage SearchAddress(SearchDetails searchDetail)
{
//13.03993,80.231867
try
{
if (!WebSecurity.IsAuthenticated)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotAcceptable);
return response;
}
List<CollegeAddress> CollegeAddress = addressService.GetAddressFromDistance(17.380498, 78.4864948, 2000);
HttpResponseMessage responseData = Request.CreateResponse(HttpStatusCode.Accepted, CollegeAddress);
return responseData;
}
catch (Exception e)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
return response;
}
}
And I have to call this method from client side.
When I call this method using Ajax, it's not working, the method parameter searchDetail is always null if I use Ajax.
$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
type: "json",
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
But when I call that method via HTTP request, it is working.
$http({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
data: searchDetail,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
toastr.success('Account Created successfully!', 'Account Created');
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
Why? What is the difference between them? Why is Ajax not working and HTTP is?

jQuery's ajax() sends the data with Content-type: x-www-form-urlencoded.
Angular's $http sends the data with Content-type: application/json
Your server obviously expects JSON, but you set up the $.ajax() call incorrectly for that.
According to the docs:
The method property doesn't seem to exist.
The type property is supposed to determine the type of the request (e.g. 'GET', 'POST', etc.).
In order to change the default content-type to application/json you can use the contentType property.
I have not tried it myself, but something like this should work:
$.ajax({
type: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
contentType: 'application/json; charset=utf-8'
});

$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
I assume that searchDetail is an object. This is what the docs say about the data property:
... It is converted to a query string, if not already a string.
So if the server expects JSON then you have to convert it to JSON first:
data: JSON.stringify(searchDetail),
And as #ExpertSystem has pointed out you have to change method to type.

First you are duplicating the HttpPost, so just keep the second (and remove the namespace)
Second you want search detail to come from the body so decorate it with [FromBody]
[HttpPost]
public HttpResponseMessage SearchAddress([FromBody]SearchDetails searchDetail)
{

Related

HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

I'm trying to make a post with javascript using ajax to a spring controller
$("#crear").click(function () {
var user = document.getElementById("user").value;
var client = document.getElementById("client").value;
var documents = document.getElementById("documents").value;
if (user==null||client==null||documents==null){
document.getElementById("error").innerHTML='FALTAN COSASsssssssssss';
alert('Rellene todo los campos!')
}
const data={
fecha_inicio:'A',
id:'A',
fecha_entrega:'A',
usuario:{
nombre:user
},
cliente: {
nombre:client
}
}
$.ajax({
url: urlCrearAlta,
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: data,
success: function(data) {
// ...
}
});
$.post(urlCrearAlta,JSON.stringify(data),function (data,satus){
console.log('${data} and status is ${status}')
});
document.getElementById("error").innerHTML=user+client+documents;
});
and java code
#RequestMapping("/altas")
#RestController
public class AltaRestController {
private AltaController altaController;
public AltaRestController(AltaController altaController) {
this.altaController = altaController;
}
#PostMapping("/create-alta")
public void createAlta(#RequestBody AltaDTO altaDTO) {
altaController.createAlta(altaDTO);
}
I'm getting the error Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
When i use $.ajax it does not send any request, just when i use $.post it send the request
The problem seems to be how you are using the $.post method. jQuery uses the application/x-www-form-urlencoded;charset=UTF-8 contentType on post by default if you don't specify another contentType. Combined with the #RequestBody annotation at backend (which requires application/json by default) it results in the seen exception and 415 status code.
The solution to this problem should be fairly easy, just add the correct configuration for the .post method, something like this:
$.post({
url: urlCrearAlta,
type: "POST",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(data)
})
.done((data, status) => {
console.log(data, status);
//do whatever you like with data and status
});
Also, as stated in jQuery documentation here, $.post is just a shorthand method for $.ajax, so if $.ajax doesn't work and $.post does, there should be something wrong in how you configure the request or how you handle the callbacks methods. The major suspect for me would be the success function you specify in the $.ajax request, check there is nothing wrong in there, or just use the other callback methods, like .done, .fail and .always

How to httppost a list of objects?

I have this list of objects which I need to send from my angularjs javascript code:
var dataToSend = [{
SubId: "c9cb1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah"
}, {
SubId: "aaaa1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah2"
}]
I've tried these different variations but none of them are working:
1.
$http.post("url",
{
dataType: 'json',
headers: {
contentType: "application/json; charset=utf-8",
},
method: "POST",
data: dataToSend,
}).then...
2.
$http.post("url",
{
data: $.param(dataToSend),
}).then...
3
$http.post("url",
{
data: angular.toJson(dataToSend),
}).then...
4
$http.post("url",
{
data: { customers: dataToSend },
}).then...
5
$http.post("url",
{
data: JSON.stringify({ customers: dataToSend }),
}).then...
My API side code is (I have tried with [FromBody] attribute but no luck there):
[HttpPost]
public async Task<JsonResult> CreateCustomers(List<Customer> customers)
{
// customers is always null
}
And this is my Customer.cs:
public partial class Customer
{
public System.Guid SubId { get; set; }
public string CustomerName { get; set; }
}
Can you please help me? I have tried posting to CreateCustomers(Customer c) without using a list and its working as expected. But when I use a list, its always coming as null on the other side.
EDIT:
$.ajax is working but $http.post isn't. Any idea why?
var request = $.ajax({
dataType: "json",
url: "url",
method: "POST",
data: { '': dataToSend }});
Are you sending JSON ( Include dataType: 'json')
$http({
url: "url",
dataType: 'json',
method: 'POST',
data: dataToSend,
headers: {
contentType: "application/json; charset=utf-8",
}
})
In C# add FromBody in parameter
[HttpPost]
public async Task<JsonResult> CreateCustomers([FromBody]]List<Customer> customers)
{
// customers is always null
}
More on Ajax parameters
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc.
This should work. post full code if you face issue
use [ModelBinder] in front of your param.
[HttpPost]
public async Task<JsonResult> CreateCustomers([ModelBinder]List<Customer> customers)
{
// customers is always null
}
Web API only uses model binding for simple types, falling back on formatters for everything else. Adding [ModelBinder] forces the complex types to use model binding anyway.
Your post data is not matched with the parameter List<Customer>.
Change your server side method to something like:
[HttpPost]
public async Task<JsonResult> CreateCustomers(JObject queryParam)
{
// populate your list here
// for eaxample : var customers = queryParam["customers"].ToString();
}
And also you can use this code to send data to the server:
$http({
url: 'url',
dataType: 'json',
method: 'POST',
data: jsonData,
headers: { "Content-Type": "application/json" }
}).success(function(response){ $scope.response = response;
}).error(function(error){ $scope.error = error; });

how to pass java script values to controller using post method in .net core application?

I am developing .net core application.i need to pass java script values to my controller using Post method. i am using java script code is below
data = {'imageValue':'some test'}
$.ajax({
type: 'Post',
url: '/Home/UploadData',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (data) {
alert(data);
console.log('sample');
},
error: function(){
}
});
my controller is
[HttpPost]public string UploadData([FromBody] string imageValue)
{return imageValue;} but imageValue always it return null.if any mistake in my code please solve the problem.
When you make the ajax call, you should stringify the javascript object and send it. You can use the JSON.stringify method to convert the js object to it's JSON string equivalent.
var data = {'imageValue':'some test'}
$.ajax({
type: 'Post',
url: '/Home/UploadData',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (data) {
console.log('sample', data);
},
error: function(){
}
});
Now since the ajax call is sending the data in the request body (since it is a POST request),You need to decorate the HttpPost action method parameter with [FromBody] attribute so that model binder knows it should read the data from the request body and map to the method parameter(YourViewModel) object.
public IActionResult UploadData([FromBody] YourViewModel d)
{
return Json(d);
}

Angular js $http post not working

I am using http post to get the data from a webservice using the following code..
$http({
method: "post",
url: "SurveyQuestions.asmx/GetSurveyQuestions",
data: JSON.stringify({"empl_id" : '12345' , "Year" : '2015' }),
headers: { 'Content-Type': 'application/json' },
dataType: "json",
contentType: "application/json; charset=utf-8",
}).success(function (response) { //do something})
The above code is working fine using "get" without parameters.
and my webservice for the post is
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False)> _
Public Sub GetSurveyQuestions(ByVal Empl_id as string, ByVal Year as string)
Try
//get list of records
Dim js As JavaScriptSerializer = New JavaScriptSerializer
Context.Response.Write(js.Serialize(listSurveyQuestions))
Catch ex As Exception
End Try
End Sub
Web service is executing fine and returning the data to the Method, but the response is empty in the $http and errored out.
you just try to pass the object only adding at the last in url.
This my case i am just adding the employee Id. if you send only employee object only it will also correct.
$scope.removeEmployee = function(employee) {
var method = 'DELETE';
var url = 'http://localhost:8080/AngularJSWithRestful/rest/product/Delete/' + employee.id ;
$http({
method : method,
url : url,
}).then(function successCallback(response) {
$scope.product = response.data.product;
}, function errorCallback(response) {
});
};
Because you are retrieving data and there are no changes being executed on your server (according to your comment) the best thing to do would be to change it to a HttpGet method. Then in angular you should use params property in the passed object to the $http function. This is because HttpGet does not support a message body. From the documentation:
params – {Object.<string|Object>} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.
Your changed code:
$http({
method: "GET",
url: "SurveyQuestions.asmx/GetSurveyQuestions",
params: {"empl_id" : '12345' , "Year" : '2015' }, // use the params property
headers: { 'Content-Type': 'application/json' },
dataType: "json",
contentType: "application/json; charset=utf-8",
}).then(function (response) { //do something})
Also note that success and error are being marked as obsolete by the angular team. The recommended approach is to use then instead. See the same documentation link.
Deprecation Notice
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
See also AngularJS passing data to $http.get request

Javascript & Node.js - make a JSON request

in this Question I read that in node.js you can distinguish between html requests and json requests like so:
app.get('/route', function (req, res) {
if (req.is('json')) res.json(data);
else if (req.is('html')) res.render('view', {});
else ...
});
now my question is how do you make a request that is interpreted as json in node server?
cause I tried with $.ajax and $.getJson and typed in the browser and all were html requests.
this is my request
$.ajax({ type: 'GET', url: "/test", dataType:"json", success: function(data){log(data)}})
The req.is method checks the incoming request type by inspecting the Content-Type header therefore you need to make sure this header is set in the request before it's sent up e.g.
$.ajax({
type: 'GET',
url: '/route',
contentType: "application/json; charset=utf-8",
....
});
However, the Content-Type header is used to determine the format of the request body, not the response. It's recommended you use the Accept header instead to inform the server of what type of format is appropriate for the response e.g.
app.get('/route', function (req, res) {
if (req.accepts('html')) {
res.render('view', {});
} else if (req.accepts('json')) {
res.json(data);
} else {
...
}
});
Then on the client, you don't need to worry about the Content-header but rather the Accept header, and jQuery already provides a handy little method for that
$.getJSON('/route', function(data) {
...
});
Try setting the contentType parameter
$.ajax({
type: 'GET',
url: 'your_url',
data: {
test: "test"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
....
});
EDIT:
You can use the request Module
all you have to do is
var request = require('request');
var options = {
uri: 'your_server_side_url',
method: 'POST',
json: {
"data": "some_data"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body.id) // Print the shortened url.
}
});
Check out that github link. May be that module will make your life easier

Categories