I have to send json object as a value with a key.
My Code:
var req = {
method: 'POST',
url: clientAdd_url,
headers: {
'Content-Type': 'application/json'
},
data: {Contact: $scope.clientinfo}
}
Contact is a key and $scope.clientinfo is a json object. But it's not working.
I checked in Postman, the format is like:
{
Contact: {
"BillingDetails": {
"CompanyName": "Shangrila Handicraft Shop",
"Address": "Kamaladi"
},
"ContactDetails": {
"ContactName": "Shyam Shrestha",
"ContactEmail": "shyam#gmail.com",
"ContactPhone": 9808909090
},
"ShippingDetails": {
"ShippingName": "Shangrila Handicraft Shop",
"ShippingAddress": "Kamaladi"
},
"Notes": "Test from Postman"
}
I would be grateful for your help.
place all those in to a obj as below...
$scope.datelvl = { "date": $scope.date, "tanklevel": $scope.Tank_level };
later call to backend controller for method like below:
$.ajax({
type: 'POST',
url: apiUrl + 'yourcontrollername/methodname',
data: datelvl,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function (data)
{
}
$scope.clientinfo looks like its a JSON object. By what I understand from your question, looks like you want to send $scope.clientinfo as a string. For that you could convert the JSON object to a string using the JSON.stringify
data: {"Contact": JSON.stringify($scope.clientinfo)}
see: http://www.json.org/js.html
Try this.It might useful.
angular.module('appCtrl1', []).controller('AppCtrl',function($scope,$http){
var tempData = {"Contact": $scope.clientinfo};
$http({
method: 'POST',
url: serverURL,
headers: { "Content-Type": "application/json" },
data: tempData,
}).success(function(data, status, headers) {
console.log(data);
}).error(function(data, status, headers) {
console.log(data);
});
}
Thank you everyone. I was told to send json data with a key as I have stated the original format though it has been little edited. So I was having a hard time. I have used the normal json post of angular in my projects. But since it was not the json, I could not send data through any process. I think many of you didn't get my question. But anyway I am so much thankful for your concern. This problem is solved. They made changes in their end.
Related
Using an S3 MultipartUpload I need the ETag header from the AngularJS $http.put request. However I don't seem to be able to read the value. Any help is appreciated. Thanks!
$http({
method: 'PUT',
url: url,
headers: {
'Content-Type': filetype,
'Access-Control-Expose-Headers': 'ETag'
},
data: part
})
.then(function(response) {
let test1 = response.headers("ETag");
let test2 = response.headers();
console.log(test1, test2); // ---> null {content-length: '0'}
})
.catch(function(error) {
console.log(error);
});
Found out you need to update the CORS of the S3 Bucket:
"ExposeHeaders": [
"ETag",
"x-amz-meta-custom-header"
]
Hi I am developing one application using web api2 and angularjs. Finding hard time to send data to web api methods. I am having problem to send data as objects n PUT and POST methods. In delete and getbyid methods i am able to send single parameter but i am not able to send data as object. I am receiving null as below.
I am calling as below using angularjs.
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: sub,
url: '/NCT_Users/',
// contentType: "application/json"
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
}
If i comment header and uncomment contentType in above code I am getting totally null object as below.
May i know why i am not able to bind object to model? Any help would be appreciated. Thank you.
var person = {firstName:"John", lastName:"Doe", age:46};
$http.post('url', person)
.success(function (response){
alert(response);
});
accesstoken is defined variable.you can define your variables to pass it to server
var person = {
firstName:"John",
lastName:"Doe",
age:46
};
$http.post('url', person)
.success(function (response) {
alert(response);
});
try this way.
var sub = {
User_CreatedDate: "",
UserEmailId: "",
User_Id: "",
User_MobileNum: "",
User_Name: "",
User_Password: "",
User_Role: "",
User_Status: "",
User_UpdateDate: ""
};
$http.post('/NCT_Users/', sub).success(function (response) { alert(response); });
the fields are filled by you
It happens like this because you are sending an JS Object via an 'application/x-www-form-urlencoded' header. You have to send the data as parameters, try this updated function:
this.saveSubscriber = function (sub) {
return $http({
method: 'POST',
data: $.param(sub),
url: '/NCT_Users/',
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
I've asked something like that before, but here are slightly different cases and more details.
I have a handler on the server side which is accepting multipart/form-data POST requests. Request contains number of POST parameters and one more parameter which should contain image file (this last parameter may exist or may not exist). How to send such requests using angularJS?
I've tried number of options (all of them for know without file uploading) but none of them works. I'm getting wrong result because absence of Content-Type: multipart/form-data in the HTTP request, or getting exception from Jetty-based Spark web-services tool (pleas don't confuse with Apache Spark) which sounds like "..."Missing initial multi part boundary..." - depending on the request details.
I've tried this:
return $http({
method: 'POST',
url: editCompanyUrl,
headers: {'Content-Type': 'multipart/form-data'},
data: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and this for example
return $http({
method: 'POST',
url: editCompanyUrl,
headers: {'Content-Type': undefined},
data: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
Could you please help? What is the right way to send multipart requests?
Thank you.
Kind regards, Artem.
$http provides an option : params.
Use params: instead of data:
$http({
url: url,
method: "POST",
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
}).success(function(data, status, headers, config) {
//SUCCESS
}).
error(function(data, status, headers, config) {
//ERROR
});
Can you show us the complete error. And also your server side code. To get multi part content in Spark, you have to use this at your server side:
MultipartConfigElement multipartConfigElement = new MultipartConfigElement("Yourstoragedirectory");
request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);
System.out.println(request.raw().getPart("file"));
Also make sure you have the latest version of spark.
I'm trying to send HTTP request using the following code:
var editCompanyUrl = 'http://X.X.X.X:YYYY/editCompany';
var userId = localStorage.getItem("UserId");
var token = localStorage.getItem("Token");
var companyId = localStorage.getItem("companyId");
return $http({
method: 'POST',
url: editCompanyUrl,
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and handler of the request on the server side accepts requests with Content-Type: multipart/form-data. How can I add this content type to the request? I've tried many advices and tips from tutorials but no success. Could you please help me? In addition to it - what should I do when I will add a file with an image to this request? Can I just add it as additional parameter of the request?
Thank you very much!
Angular POST must be like below code.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
it should have data:{ }
so try to put your params: inside the data and it should work.
The following is a GET request I am making to Parse.com's RESTful API. I want to structure the request to only retrieve records that have been received today.
$http({
method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
// WHAT DO I PUT HERE?
createdAt: /* greater than 8am today, less than or equal to current time */
}
})
After reading from the Parse API docs about Query Constraints, I've modified the $http GET. However, it still returns all Orders.
var startDate = new Date();
var currentTime = new Date().getTime();
startDate.setHours(8);//set time to 8 am.
$http({ method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
where: {
"createdAt": { "$gte": startDate, "$lte": currentTime }
}
}
})
EDIT 1: Upon structuring my get request like so: I receive a 400 HTTP error, containing the following:
code: 107
error: "invalid date {1.433264918052e+12}"
EDIT 2 (SOLVED): I've solved the issue. After resolving the structure of the params property, I learned that the Parse API expects an ISO format DateTime. So, my final version looks like this:
var startDate = new Date().toISOString();
var currentTime = new Date().getTime().toISOString();
startDate.setHours(8);//set time to 8 am.
var deferred = $q.defer();
$http({ method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
where: {
"createdAt": { "$gte": startDate, "$lte": currentTime }
}
}
})
If someone would like to take this opportunity and give a thorough explanation, I would be happy to give them the answer (e.g. what benefit is there for Parse to use ISO over standard Unix epoch time?).
You can pass the from and to dates timestamp to pass a range of date. Try something like this.
var startDate = new Date();
startDate.setHours(8);//set time to 8 am.
$http({
method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
createdFrom: startDate.getTime(),
createdTo: new Date().getTime()
}
});
On the server side you can convert the timestamp to date object to pass it to DB stored proc or query.
Realized that I posted the answer in the question a long time ago. Updating this with an official answer for posterity.
I've solved the issue. After resolving the structure of the params property, I learned that the Parse API expects an ISO format DateTime. So, my final version looks like this:
var startDate = new Date().toISOString();
var currentTime = new Date().getTime().toISOString();
startDate.setHours(8);//set time to 8 am.
var deferred = $q.defer();
$http({ method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
where: {
"createdAt": { "$gte": startDate, "$lte": currentTime }
}
}
})