AngularJS http POST using form not working - angularjs

// http.post gives 404 error no matter what so I am trying with GET
// $scope.user.name etc does bring correct values from form
// I think we can't view FormData on console but passing the 'data
// after appending $scope values, runs the get request without any //data
// so I tried to make a plain dummy object 'obj' with static
// values to check get request
// this too runs URL with no data
// response that i recieve is //{"success":"no","data":"","error_code":"DSWS3","error_descriptio//n":"Server Error"}
//and yes, testing the API with same parameters on Postman does //give correct result
var data = new FormData();
data.append('name', $scope.user.name);
data.append('city', $scope.user.city);
data.append('address', $scope.user.address);
var obj = {
name: "fefe",
city: "1",
address: "fofo"
};
var data = JSON.stringify(obj);
console.log(data);
//alert(JSON.stringify(data));
$http.get('http://lowc----.com/storeManager/createParentStore?token=6fc72be8-4153-432e23a9e', data, {
withCredentials: false,
transformRequest: angular.identity,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
console.log(response)
});
I am stuck at making this HTTP POST work.. I am getting the data from form and I want to append it at the end of the URL like this baseURL+token+&name=store%20name&city=this&address=that
It gives two errors also how can I make an object of the data I received from form to pass to the http data.
1. POST (url i provided) 404 not found
2. Possibly unhandled rejection: {"data":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST /storeManager/createParentStore</pre>\n</body>\n</html>\n","status":404,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://lowcost-env.2u3kmcbg4k.us-west-2.elasticbeanstalk.com/storeManager/createParentStore?token=6fc72be8-4153-432e-9191-64a9e3b23a9e","data":{"name":"$scope.user.name","city":"$scope.user.city","address":"$scope.user.address"},"headers":{"Content-Type":"application/x-www-form-urlencoded","Accept":"application/json, text/plain, */*"}},"statusText":"Not Found"}
Here is my HTML
<form class="form-horizontal" name="userForm" ng-submit="submitForm()">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><strong>Add new </strong></h3>
</div>
<div class="panel-body form-group-separated">
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label">Name</label>
<div class="col-md-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-pencil"></span></span>
<input type="text" class="form-control" name="name" ng-model="user.name" />
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label">City</label>
<div class="col-md-6 col-xs-12">
<select class="form-control select" name="city" ng-model="user.city">
<option>Islamabad</option>
<option>Rawalpindi</option>
<option>Karachi</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label">Address</label>
<div class="col-md-6 col-xs-12">
<textarea class="form-control" rows="5" name="address" ng-model="user.address"></textarea>
</div>
</div>
</form>

You should not pass the $scope variables in quotes, remove the quotes and pass it as below,
var data = new FormData();
data.append('name', $scope.user.name);
data.append('city', $scope.user.city);
data.append('address', $scope.user.address);
$http.post('http://low----.com/storeManager/createParentStore?token=6fc72be3-432e-9191-64a9e3b23a9e', data, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
}).success(function(response) {
console.log(response)
});

Try this:
$http({ url:'http://low----.com/storeManager/createParentStore?token=6fc72be3-432e-9191-64a9e3b23a9e',
method: "POST",
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
data: JSON.stringify($scope.user),
responseType: 'arraybuffer'
}).success(function(data, status, headers, config) {
console.log("success");
}).error(function(data, status, headers, config) {
console.log("error");
return null;
});

Related

angular: form submit with dynamic dropdown list

I have a small form and in that form i have a drop down list. List items are generated dynamically.
$http({
url: 'alljobs.php',
method: "GET",
params: {
uid: viewer_id
}
}).success(function(data) {
$scope.jobss = data.content;
});
Below is the code for form submit.
$scope.formprofile33 = function() {
var allData33 = {
'msg': $scope.msg,
'emp_id': viewer_id,
'job_id': job.job_id,
'job_title': $scope.jobss.SelectedOption.job_title,
// 'job':job,
'user_id': user_id
}
$http({
method: 'POST',
url: 'send_msg.php',
data: allData33,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
if (!data.success) {
$scope.message = data.errors.message;
} else {
$scope.message = '';
alert('Your message has been sent.');
$scope.message = '';
}
});
};
Here is the form.
<form name="formProfile33" method="post" id="formProfile33" role="form" ng-submit="formprofile33()">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="row">
<div class="col-xs-10">
<div class="col-xs-12 s_ma">
<select id="job" name="job" class="search_color selectors form-control" ng-model="job" required="required" ng-options="item.job_title for item in jobss track by item.job_id">
<option value=""> Select Job *</option>
</select>
</div>
<textarea name="msg" ng-model="msg" class="form-control textbox1" id="msg" placeholder="Write your message" required="required" rows="3"></textarea>
</div>
</div>
</div>
</div>
<center>
<button type="submit" class="btn btn-home" name="btn-save1" id="btn-save1" required="required"><i class="icon ion-email"></i> Send Message </button>
</center>
</div>
</form>
Problem is i am not able to pass dropdown value and id during form submit.
I am getting below error.
TypeError: Cannot read property 'job_title' of undefined
Please advise how can i submit the form with dropdown id and value.
Your example set a job item to the scope field "job" => ng-model="job",
the full selected item is accessible with $scope.job.
Try $scope.job.job_title or $scope.job.job_id
A print out in your html is anytime a good helper: Full job item: {{job | json}}
https://plnkr.co/edit/VenFVchI0brGZNC2Q7Fn?p=preview

AngularJS access $http return json array

i have older post which i deleted i solved it there.
I have other issue:
I have this data array came from PHP with $http(i use console.log):
I can't access that data with ng-repeat:
ibids.controller("auctions",function($http){
var req = {
method: 'POST',
url: 'includes/bids.php',
headers: {
'Content-Type': 'json'
},
data: 'q=getAuctions'
}
$http(req).then(function(req){
console.log(req);
var auctionslist = req.data;
}, function(){
});
});
html:
<body ng-controller="auctions as auction">
<input type="text" value="test" ng-model="man">
{{man}}
<hr>
<div class="search" >
<input type="text">
<div class="res" ng-repeat="x in auction.auctionslist">
{{x}}
</div>
</div>
</body>
What is wrong here ? i recive json data from php and perfect assign to data array in $http .when i use console.log(req) this is what you see in the pictures and its recive the json array perfect.
i don't know how to use ng-repeat on that data .
You have to use $scope and add a property on it for this data and use it in template
ibids.controller("auctions",function($http, $scope){
var req = {
method: 'POST',
url: 'includes/bids.php',
headers: {
'Content-Type': 'json'
},
data: 'q=getAuctions'
}
$http(req).then(function(req){
console.log(req);
$scope.auctions = req.data;
}, function(){
});
});
and in html
<body ng-controller="auctions">
<input type="text" value="test" ng-model="man">
{{man}}
<hr>
<div class="search" >
<input type="text">
<div class="res" ng-repeat="auction in auctions">
{{auction}}
</div>
</div>

Sharepoint 2013 App AngularJS: lookup field causing error when adding to list "A type named 'SP.Data.TeamsListItem' could not be resolved by the model

I have a Players List with a lookup field for Team Name linked to the Teams List.
When trying to add or update the Players List I am getting the error
"A type named 'SP.Data.TeamsListItem' could not be resolved by the model. When a model is available, each type name must resolve to a valid type.".
The guid for the players list is '16a03b71-07ea-49c4-ab14-419b51047119'.
The guid for the teams list is '2a2916c2-22fb-4588-bca1-83479a4d85b2'.
This is the contents of data field when the error occurs:
<pre>
"{\"__metadata\":{\"type\":\"SP.Data.PlayersListItem\"},\"Title\":\"Bill\",\"PlayerPosition\":\"Goalie\",\"Birthdate\":\"2/21/1999\",\"TeamName\":{\"__metadata\":{\"id\":\"Web/Lists(guid'2a2916c2-22fb-4588-bca1-83479a4d85b2')/Items(1)\",\"uri\":\"https://app-2971fdcf9ede6a.rawtecapps.com/sites/raiders/AngularCRM/_api/Web/Lists(guid'2a2916c2-22fb-4588-bca1-83479a4d85b2')/Items(1)\",\"etag\":\"\\\"1\\\"\",\"type\":\"SP.Data.TeamsListItem\"},\"Id\":1,\"Title\":\"aa\",\"ID\":1,\"$$hashKey\":\"object:176\"},\"Season\":\"2015\"}"
</pre>
Definition of my Lookup field.
<pre>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Field
ID="{7853bbf2-9fd7-4f85-aca8-269d8f967650}"
Name="TeamName"
DisplayName="Team Name"
Type="Lookup"
List="Lists/Teams"
ShowField="Title"
Required="FALSE"
Group="Custom Site Columns">
</Field>
</Elements>
</pre>
Content Type for Teams List:
<pre>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/"><ContentType ID="0x0100A379177A3533447D9B6546708F7DFD2D" Name="Teams" Group="Custom Content Types" Description="Teams Content Type" Inherits="FALSE" Version="0">
<FieldRefs>
<FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" DisplayName="Team Name" Required="TRUE" Name="Title" />
<FieldRef ID="{fce82853-3f44-4cc9-8f71-eb6506be0e9e}" DisplayName="Team City" Required="FALSE" Name="TeamCity" />
</FieldRefs>
</ContentType>
</pre>
playersnew.html page:
<pre>
<div class="form-horizontal">
<fieldset>
<div class="form-group">
<label for="txtID" class="col-lg-2 control-label">ID:</label>
<div class="col-lg-6">
<input id="txtID" type="text" readonly class="form-control" ng-model="player.ID">
</div>
</div>
<div class="form-group">
<label for="txtPlayerName" class="col-lg-2 control-label">Player Name:</label>
<div class="col-lg-6">
<input id="txtPlayerName" type="text" class="form-control" ng-model="player.Title">
</div>
</div>
<div class="form-group">
<label for="txtPlayerPosition" class="col-lg-2 control-label">Player Position:</label>
<div class="col-lg-6">
<input id="txtPlayerPosition" type="text" class="form-control" ng-model="player.PlayerPosition">
</div>
</div>
<div class="form-group">
<label for="txtBirthdate" class="col-lg-2 control-label">Birthdate:</label>
<div class="col-lg-6">
<input id="txtBirthdate" type="text" class="form-control" ng-model="player.Birthdate">
</div>
</div>
<div class="form-group">
<label for="txtTeamName" class="col-lg-2 control-label">Team Name:</label>
<div class="col-lg-6" ng-controller="TeamDropDownController">
<select name="teams" ng-model="player.TeamName" ng-options="team.Title for team in teams">
<option ng-repeat="team in teams" value="{{team.Id}}">{{team.Title}}</option>
</select>
</div>
</div>
<div class="form-group">
<label for="txtSeason" class="col-lg-2 control-label">Season:</label>
<div class="col-lg-6">
<input id="txtSeason" type="text" class="form-control" ng-model="player.Season">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2">
<input id="cmdSave" type="button" class="button" value="Save" data-ng-click="addPlayer()" />
</div>
</div>
</pre>
Angular JS (playersnew Controller):
><pre>
app.controller('playersnewController',
function ($scope, $location, wingtipCrmService) {
$scope.player = {};
$scope.player.Title = "";
$scope.player.PlayerPosition = "";
$scope.player.Birthdate = "";
$scope.player.TeamName = "";
$scope.player.TeamName.Id = "";
$scope.player.TeamName.Title = "";
$scope.player.Season = "";
$scope.addPlayer = function () {
var playerName = $scope.player.Title;
var playerPosition = $scope.player.PlayerPosition;
var birthdate = $scope.player.Birthdate;
var teamName = $scope.player.TeamName;
var teamNameId = $scope.player.TeamName.Id;
var teamNameTitle = $scope.player.TeamName.Title;
var season = $scope.player.Season;
wingtipCrmService.addPlayer(playerName, playerPosition, birthdate, teamName, teamNameId, teamNameTitle ,season)
.success(function (data) {
$location.path("/playershome");
});
}
} );
</pre>
Angular JS (service for addplayer):
> <pre>
service.addPlayer = function (PlayerName,PlayerPosition,Birthdate,TeamName,TeamNameId,TeamNameTitle,Season) {
var restQueryUrl = "../_api/web/lists/getByTitle('Players')/items";
var playerData = {
__metadata: { "type": "SP.Data.PlayersListItem" },
Title: PlayerName,
PlayerPosition: PlayerPosition,
Birthdate: Birthdate,
TeamName: TeamName,
Season: Season
};
var requestBody = JSON.stringify(playerData);
return $http({
method: 'POST',
url: restQueryUrl,
contentType: "application/json;odata=verbose",
data: requestBody,
headers: {
"Accept": "application/json; odata=verbose",
"X-RequestDigest": requestDigest,
"content-type": "application/json;odata=verbose"
}
});
}
</pre>
Angular JS (TeamDropDownController and service):
<pre>
app.controller('TeamDropDownController',
function ($scope, wingtipCrmService) {
wingtipCrmService.getDropDownTeams().success(function (data) {
$scope.teams = data.d.results;
})
});
</pre>
<pre>
service.getDropDownTeams = function () {
var restQueryUrl = "../_api/web/lists/getByTitle('Teams')/items/" +
"?$select=ID,Title";
return $http({
method: 'GET',
url: restQueryUrl,
headers: { "Accept": "application/json; odata=verbose" }
})
}
</pre>
I am new to developing sharepoint apps and Angular JS. I have been trying to figure out a solution for this issue for over a week and in the process I have learned a great deal.
I am using TeamDropDownController to load the select statement with team names and then using playersnewcontroller to add new player record.
The add player javascript works until I added the code to include the TeamName field. I am afraid that the way I am loading the dropdown with a controller is causing a problem with the playersnewController.
The error message:
"A type named '{ListItemEntityTypeFullName}' could not be resolved by the
model. When a model is available, each type name must resolve to a
valid type.".
commonly occurs when List Item entity with the specified name could not be found. In your case it means there is no entity with name SP.Data.PlayersListItem.
The following endpoint allows to properly determine list item entity name:
Uri: /_api/lists/getbytitle('{List Title}')?$select=ListItemEntityTypeFullName
Method: GET
The following jQuery example demonstrates how to dynamically determine entity type name while creating list item:
function createListItem(webUrl,listTitle,itemProperties)
{
var requestUri = webUrl + "/_api/lists/getbytitle('" + listTitle + "')?$select=ListItemEntityTypeFullName";
return executeJson({url:requestUri}).then(function(data){
var requestUri = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
itemProperties['__metadata'] = {'type': data.d.ListItemEntityTypeFullName};
return executeJson({url: requestUri, method: 'POST', data: itemProperties});
});
}
var properties = {'Title':'John Doe'};
createListItem(_spPageContextInfo.webAbsoluteUrl,'Contacts',properties)
.done(function(data)
{
console.log('List item has been created');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
function executeJson(options)
{
method = options.method || 'GET';
headers = options.headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if (typeof options.data != 'undefined') {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
To fix my issue I added the player record without filling the TeamName lookup field. Then immediately performed an update of the player record with the TeamName field information.

SharePoint App can't Post form data to REST using Angular $resource

I am using angular to post form data to SharePoint's REST service, but it is not posting. I am able to "get" JSON data without issue and believe I am missing something obvious. I also don't receive an error message.
Here is sample REST data, of which I would like to create another entry in the "value" object:
{
"value": [
{
"FileSystemObjectType": 0,
"Id": 1,
"ContentTypeId": "0x010400AF4ACA1755AD48428EF182FA566973E6",
"Title": "Test1",
"Body": "<div class=\"ExternalClass5217CB82669B4C4B901FC90EF1D1734F\"><p>Test 1 body​</p></div>",
"Expires": null,
"RequesterId": null,
"ManagerId": null,
"ID": 1,
"Modified": "2015-03-11T21:52:33Z",
"Created": "2015-03-11T21:52:33Z",
"AuthorId": 12,
"EditorId": 12,
"OData__UIVersionString": "1.0",
"Attachments": false,
"GUID": "e46af534-f488-4389-ad7e-726ed2af0d52"
}
]
}
Here is my form (the controller is tied to the page via routing and is working):
<form name="newItem" class="form-horizontal" data-ng-submit="createItem()" novalidate>
<fieldset>
<div class="form-group">
<label class="col-lg-2 control-label" for="title">Title *</label>
<div class="col-lg-10">
<input class="form-control" name="title" id="title" type="text" data-ng-model="itemtitle" placeholder="Add your title (Limited to 70 characters)" data-ng-maxlength="70" required>
({{70 - newItem.title.$viewValue.length}} Characters Remaining)
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label" for="body">Body *</label>
<div class="col-lg-10">
<textarea class="form-control" name="body" id="body" data-ng-model="itembody" rows="4" placeholder="Add your body (Limited to 500 characters)" data-ng-maxlength="500" required> </textarea>
Your summary will be displayed as follows ({{500 - newItem.body.$viewValue.length}} Characters Remaining):<br /> {{itembody}}
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-default" data-ng-click="cancel()">Cancel</button>
<button class="btn btn-primary" data-ng-disabled="newItem.$invalid">Submit</button>
<p data-ng-show="newItem.$invalid" class="help-block validsubmit">The submit button will become "active" once all fields are properly filled out.</p>
</div>
</div>
</fieldset>
Here is my controller:
// Add new item
appControllers.controller('appItemPostCtrl', ['$scope', '$location', 'appItems', function ($scope, $location, appItems) {
var itemEntry = new appItems;
$scope.createItem = function () {
itemEntry.Title = $scope.itemtitle;
itemEntry.value.$save();
$location.path('/');
}
$scope.cancel = function () {
$location.path('/');
}
}]);
Here is my service (I wonder if I need the "save"):
appServices.factory('appItems', ['$resource', function ($resource) {
return $resource("/_api/web/lists/getbytitle('Todo Task List')/Items", {},
{
'query': { method: "GET", isArray: false, headers: { 'Accept': 'application/json;odata=nometadata'}},
'update': { method: 'PATCH', headers: { 'Accept': 'application/json;odata=nometadata' } },
'save': { method: 'POST', headers: { 'Accept': 'application/json;odata=nometadata', 'content-type': 'application/json;odata=nometadata', 'X-RequestDigest': $("#__REQUESTDIGEST").val() } },
}
);
}]);
EDIT: I have added "X-RequestDigest": $("#__REQUESTDIGEST").val() header to my POST method, but it is still not working
Interesting pattern for using $resource, I haven't see it used like that before. I think the reason you can call POST is because you can't use $save on items not returned as a result of get().
Try:
appItems.save({title: $scope.itemtitle})

Angular JS + Spring 4 : Upload File and Form Data

We are using Spring 4 (Annotation based configuration) and AngularJS for building our application. In one of the usecase, we need to upload a document. On submitting the form, we need to send the form data (apart from file uploaded file, there are fields which are part of the form) and the file content as part of the POST request.
#Bean(name="multipartResolver")
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
The HTML form contents:
<form method="post" id="fromFileUpload"
enctype="multipart/form-data" ng-submit="create()">
<div class="form-group">
<label for="inputValue" class="col-md-offset-2 col-md-4 form-element">Input Value</label>
<div class="col-md-6 form-element">
<input class="form-control" ng-model="model.value"
name="val" required autofocus>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4 col-xs-12" for="file">Please
upload the file : <span class="required">*</span>
</label>
<div class="col-xs-4 input-max controls ">
<input class="inline-block" type="file" name="file"
ng-model="file" data-rule-required="true" id="file"
accept=".xls">
</div>
<span id="vaildFile" class="text-success icon-ok hide">Valid
File</span> <span id="invaildFile" class="text-error icon-remove hide">
Invalid File</span>
</div>
<div class="box-header">
<div class="actions">
<button type="submit" class="btn btn-primary">
<i class="icon-arrow-right"></i> Create
</button>
</div>
</div>
</form>
Below is the angularJS code :
$scope.create = function() {
var formData=new FormData();
formData.append("file",$scope.file);
formData.append("docData", angular.toJson($scope.model));
console.log(formData);
$http({
method: 'POST',
url: "http://localhost:8080/saprof/value",
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headers) {
return data;
}
})
.success(function(data, status) {
alert("Success");
})
.error(function(data, status) {
alert("Error");
});
};
Below is the controller Code (Annotated with #RestController)
#RequestMapping(value="/saprof/value", method=RequestMethod.POST)
public void createValue(HttpServletRequest request, HttpServletResponse response, HttpSession session){
LOGGER.info("Request is of type MultiPartRequest "+(request instanceof MultipartHttpServletRequest)); // false
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
LOGGER.info("isMultiPart Request : "+isMultipart); // false
}
Problem:
I am getting RequestFacade object as the request object and not MultiPartServletRequest. Hence i am not able to retrieve the form data + file contents from this request.
When see the request which is been sent using browser, below is the content:
Request Payload
------WebKitFormBoundaryzfZtWVlK6xH8aSyf
Content-Disposition: form-data; name="file"
[object Object]
------WebKitFormBoundaryzfZtWVlK6xH8aSyf
Content-Disposition: form-data; name="docData"
{"value":"test"}
------WebKitFormBoundaryzfZtWVlK6xH8aSyf--
Need your help in correcting my mistakes. Let me know if you need any further details. Really appreciate your help.
Regards,
Manjunath
I used this module on my own project and it worked like a charm:
danialfarid/ng-file-upload

Resources