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
Related
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
I want to pass a lot of parameters from my ajax function to my controller. Initially, I thought I would just do this using a query string but that wasn't giving me the result I wanted, although it worked it was creating an unattractive URL the more data I added.
I thought the better approach would be to take all this data I need to pass, store it as an object and pass that payload into the controller from an ajax function.
The ajax function is triggered from the .event() attribute of the KendoGrid.
Kendo Grid
#(Html.Kendo().Grid<MyProject.Models.Car>()
.Name("requirement-grid")
.Columns(columns =>
{
columns.Bound(c => c.Name);
columns.Command(command => command
.Custom("Test").Click("payload"));
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetCars", "cars"))))
As you can see from the above code, there is a custom command that I've used which triggers a function when you click on it. The function is payload and the code is as follows:
payload
function payload(e) {
e.preventDefault();
//Get row data
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Create Object
var obj = {
Name: dataItem.Name,
BHP: dataItem.BHP,
YearOfBuild: dataItem.YearOfBuild
}
//Post via Ajax
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
}
I access the data of the row that was clicked on and pass it down via the events parameter, from there I create an object and add the data to it. I then create an ajax call and try to pass it to the controllers.
The controller expects the parameter, the code is as follows but shortened for brevity.
Controller
public ActionResult Create(object[] obj)
{
return View(obj);
}
If I use "POST" in my ajax function I get an error regarding a anti-forgery token which is missing. If I use "GET" the obj parameter is always null.
The required anti-forgery cookie "__RequestVerificationToken" is not present.
Is there a better way to be doing this or is my approach incorrect?
So this should be a relatively simple change to your code. I am assuming you have an anti-forgery token loaded onto the page and the action you are posting to is protected by this. You have two solutions here:
1) Remove the requirement for the token if it isn't needed from the action in your controller
2) Provide the token as part of the data package you are sending back to the server by changing your code from
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: JSON.stringify({
array: obj
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("Success");
},
error: function (ob, errStr) {
console.log(ob.responseText);
}
});
to:
$.ajax({
type: 'POST',
url: '/Controller/Method/',
data: {
array: JSON.stringify(obj),
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log("Success");
},
error: function(ob, errStr) {
console.log(ob.responseText);
}
});
Notice I have just added a reference to the anti-forgery token as part of the data package for you and this should be read by the controller and allow the command to complete successfully for you if you have the token on the page. if not then just add the #Html.AntiForgeryToken() to the view and you should be fine.
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);
}
I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.
I am trying to make an AJAX call to the server side, using $http from my Angular App.
For sending the parameters, I tried the following:
$http({
method: "post",
url: URL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
console.log(result);
});
This is working, but it is using jQuery as well at $.param. For removing the dependency on jQuery, I tried:
data: {username: $scope.userName, password: $scope.password}
but this seemed to fail. Then I tried params:
params: {username: $scope.userName, password: $scope.password}
but this also seemed to fail. Then I tried JSON.stringify:
data: JSON.stringify({username: $scope.userName, password: $scope.password})
I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?
I think you need to do is to transform your data from object not to JSON string, but to url params.
From Ben Nadel's blog.
By default, the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type, "application/json". When we want to post the value as a FORM
post, we need to change the serialization algorithm and post the data
with the content-type, "application/x-www-form-urlencoded".
Example from here.
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {username: $scope.userName, password: $scope.password}
}).then(function () {});
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
URL-encoding variables using only AngularJS services
With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:
$httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)
$httpParamSerializer - a serializer used by Angular itself for GET requests
Example with $http()
$http({
url: 'some/api/endpoint',
method: 'POST',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}).then(function(response) { /* do something here */ });
See a more verbose Plunker demo
Example with $http.post()
$http.post(
'some/api/endpoint',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}
).then(function
How are $httpParamSerializerJQLike and $httpParamSerializer different
In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.
For example (ignoring percent encoding of brackets):
• Encoding an array
{sites:['google', 'Facebook']} // Object with array property
sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike
sites=google&sites=facebook // Result with $httpParamSerializer
• Encoding an object
{address: {city: 'LA', country: 'USA'}} // Object with object property
address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike
address={"city": "LA", country: "USA"} // Result with $httpParamSerializer
All of these look like overkill (or don't work)... just do this:
$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
`&password=${ encodeURIComponent(password) }` +
'&grant_type=password'
).success(function (data) {
The problem is the JSON string format, You can use a simple URL string in data:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.username+'&password='+$scope.password
}).then(function(response) {
// on success
}, function(response) {
// on error
});
Works like a charm with AngularJS 1.5
People, let give u some advice:
use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)
From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."
If your data model is more complex that just a username and a password, you can still do that (as suggested above)
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: json_formatted_data,
transformRequest: function(data, headers) {
return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
}
}).then(function(response) {
// on succes
}, function(response) {
// on error
});
Document for the encodeURIComponent can be found here
If it is a form try changing the header to:
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
and if it is not a form and a simple json then try this header:
headers[ "Content-type" ] = "application/json";
From the $http docs this should work..
$http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(response) {
// your code...
});
$http({
method: "POST",
url: "/server.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "name='Олег'&age='28'",
}).success(function(data, status) {
console.log(data);
console.log(status);
});
you need to post plain javascript object, nothing else
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: { id: 4, name: "Kim" }
});
request.success(
function( data ) {
$scope.localData = data;
}
);
if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side
Though a late answer, I found angular UrlSearchParams worked very well for me, it takes care of the encoding of parameters as well.
let params = new URLSearchParams();
params.set("abc", "def");
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http
.post(UrlUtil.getOptionSubmitUrl(parentSubcatId), params, options)
.catch();
This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.
This is my angular controller.
var angularJsApp= angular.module('angularJsApp',[]);
angularJsApp.controller('MainCtrl', function ($scope ,$http) {
$scope.userName ="Victoria";
$scope.password ="password"
$http({
method :'POST',
url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
data: { username : $scope.userName , password: $scope.password},
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
console.log('status',status);
console.log('data',status);
console.log('headers',status);
});
});
This is my php back-end laravel controller.
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
This is my laravel routing
Route::post('httpTest','HttpTestController#httpTest');
The result in browser is
status 200
data JSON_CALLBACK({"username":"Victoria","password":"password","callback":"JSON_CALLBACK"});
httpTesting.js:18 headers function (c){a||(a=sc(b));return
c?a[K(c)]||null:a}
There is chrome extension called postman. You can use to test your back-end url whether it is working or not.
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
hopefully, my answer will help you.
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)
{