How to send form data from Angularjs to Django - angularjs

I did the application on the sample from this lesson. Here, using DRF, a list of all added games is displayed on the page. I would really like to learn how to write a simple form of adding a new record to the database (two fields: title and description [as in the example]).
With js, I'm not very familiar with so far, so I do not know which side to get close to solving the problem.

$scope.saveUser = function(event) {
postForm({ id: 0 }, $('#FormName'), $scope, function(data) {
})
}
function postForm(postInfo, form, $scope, callback,) {
var postData = new FormData(form.get(0));
$.each(postInfo, function(key, value) {
postData.append(key, value);
});
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: postData,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
headers: {
"X-CSRFToken": app.getStorage("csrftoken")
},
beforeSend: function() {
$('#loading-image').show();
},
complete: function() {
$('#loading-image').hide();
if(typeof saveButtonId !== typeof undefined) {
$('#'+saveButtonId).removeAttr('disabled');
}
},
success: function(data) {
},
error: function(data) {
//
}
});
};

you'd be updating code in your mysite/backend folder to have some incoming route to insert data into django db using some serializer
sorry I don't have more specific details, but just wanted to convey the general idea
Here's some more information on Django serializers: http://www.django-rest-framework.org/api-guide/serializers/
another tutorial on adding an additional route to django could help

Related

How to get value from router request?

I have created an angular app. In this app, I want to add a search. for this, I have a textbox and a button. Textbox name is name="search"
I have a get method in API.
router.get('/allActivities', (req, res) => {
Activity.find({ name: req.body.search }, (err, activities) => {
if(err) {
res.json({success: false, message: err});
} else {
if(!activities) {
res.json({success: false, message: 'No recent activities found'});
} else {
res.json({success: true, activities: activities});
}
}
})
});
This is the get request. In this, I'm trying to get the text box value from angular front end
Activity.find({ name: req.body.search }, (err, activities) =>
This is MongoDB
But I'm not getting any output. The matter here is I'm not getting a value for this "req.body.search" which I used to get text box value. can anybody tell me how to do this?
if I put
Activity.find({ name: 'Roshini' }, (err, activities) =>
like this, I'm getting the output. So pretty sure that I'm not getting textbox value to this get method correctly, :/
Html side
<input ng-model="search">
Angular Controller
$http({
method: 'GET',
url: '/allActivities?search='+$scope.search
}).then(function (response) {
$scope.activities = response.data || response
}, function (response) {
alert(response)
}
);
and on backend access it by req.query.search or req.params.search rather than req.body.search

How to post data on button click using AngularJS

I have an application made with .NET core framework and pure html in the front end. I was using AJAX to post and get data.
I am new to Angular and decided to convert the front end of the application to Angular for learning purposes.
For Example, I have a button that will change the state of employees from 'Billed' to 'Available' state. The ID for available state is defined in the back end and it is '1'.
//MOVE TO BENCH BUTTON CLICK
$(document).ready(function()
{
var allVals = [];
$("#MoveToBench").click(function()
{
$('input:checkbox:checked').each(function () {
allVals.push($(this).val());
});
for (i = 0;i<allVals.length;i++){
PostBenchList(allVals[i])
}
function PostBenchList(entityId) {
var data = 'entityID='.concat(entityId).concat('&nextStateId=1');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:1783/api/Workflow?"+data,
data: data,
dataType: "text",
success: function (data) {
location.reload();
alert("Successfully added the selected Employees to TalentPool");
},
fail: function (error) {
Console.Log(error);
}
})
}
});
});
The above code is taking an array of entityID's as input. For the Angular application, the array is not required as only one entity ID will be passed.
The API controller in the backend is :
// POST api/values
[HttpPost]
public void Post(int entityId, int nextStateId)
{
JObject jsonObject = JObject.Parse(System.IO.File.ReadAllText("Config.Json"));
string jsonFile = jsonObject.GetValue("WorkfowJsonFileLocation").ToString();
var nextState = _stateServices.Get(nextStateId);
var handler = new WorkflowHandler(nextState, jsonFile, _entityServices, 1, _stateServices, _subStateServices, _appServices);
handler.PerformAction(entityId);
}
The above code worked for me and it would change the state ID of the employee(EntityID)to 1(nextStateId)
Now I have a button in AngularJS and I want it to do the same action. How would I achieve this? As I am still in the procedure of learning, I don't have a clue how to do this. Can anyone help me to achieve this? This would help me to learn and do all similar buttons.
Thank You.
You can use ng-click and call a function to post the data,
HTML:
<button ng-click="PostData()">
Click to POST
</button>
Controller:
app.controller('PostController',['$scope',function($scope)
{
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
})
}
}]);
DEMO APP

AngularJS Trigger callback after ForEach

I'm currently developing an AngularJS form which on submit pushes single or multiple participant data to an SQL database.
I'm able to push data to the SQL database, but I'm wanting to trigger a callback that redirects the user once all participant data has been successfully submitted.
At the moment on success it redirects the user but, misses the next foreach submit for the next participant.
Any and all advice would be appreciated.
AngularJS
/* Submit */
$scope.submit = function() {
var array = $scope.form.participants;
//console.log(array);
angular.forEach(array, function(value, key){
var request = $http({
method: "post",
url: 'http://xxx.co.uk/submit.php',
data: {
coachName: $scope.form.program.coachName,
contactArea: $scope.form.program.contractArea,
postcode: $scope.form.program.postcode,
programmeStart: $scope.form.program.programmeDate,
sessionDate: $scope.form.program.sessionDate,
sessionNumber: $scope.form.program.sessionNumber,
weekNumber: $scope.form.program.weekNumber,
id: value.participant.id,
attendance: value.participant.attendance,
weight: value.participant.weight,
goldBehaviours: value.participant.goldBehaviours,
stepCount: value.participant.stepCount,
creditData: value.participant.creditData,
weekOne: value.participant.weekOne,
stepOne: value.participant.stepOne,
weekTwo: value.participant.weekTwo,
stepTwo: value.participant.stepTwo,
weekThree: value.participant.weekThree,
stepThree: value.participant.stepThree,
weekFour: value.participant.weekFour,
stepFour: value.participant.stepFour,
weekFive: value.participant.weekFive,
stepFive: value.participant.stepFive
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data) {
//console.log(data);
$location.path("/thankyou");
});
});
};
Data
{
"program":{
"coachName":"AD",
"contractArea":"Berkshire",
"postcode":"NN1",
"programmeDate":"2016-08-15T23:00:00.000Z",
"sessionDate":"2016-08-16T23:00:00.000Z",
"sessionNumber":"1",
"weekNumber":"2"
},"participants":[
{"participant":{"id":"AW01","attendance":"Did Not Attend","weight":"1","goldBehaviours":"2","stepCount":"3","creditData":"","weekOne":"4","stepOne":"4","weekTwo":"5","stepTwo":"5","weekThree":"6","stepThree":"6","weekFour":"7","stepFour":"7","weekFive":"8","stepFive":"8"}},
{"participant":{"id":"AW02","attendance":"Attended","weight":"2","goldBehaviours":"3","stepCount":"4","creditData":"","weekOne":"5","stepOne":"5","weekTwo":"6","stepTwo":"6","weekThree":"7","stepThree":"7","weekFour":"8","stepFour":"8","weekFive":"9","stepFive":"9"}}
]
}
You can inject $q to your controller/service and use $q.all method (you can also use native Javascript Promise if you're not worried about old browsers support).
The all method takes an array of promises and resolve when all promises in the array resolve (it will reject if any of the promises reject).
$scope.submit = function() {
var array = $scope.form.participants;
var promises = [];
//console.log(array);
angular.forEach(array, function(value, key){
promises.push($http({
method: "post",
url: 'http://xxx.co.uk/submit.php',
data: {
coachName: $scope.form.program.coachName,
...
...
...
stepFive: value.participant.stepFive
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}));
});
$q.all(promises).then(function() {
$location.path("/thankyou");
});
};
You are telling it to redirect with each iteration, not after all iterations have been completed. Try moving your redirect like so:
angular.forEach(array, function(value, key){
var request = $http({
method: "post",
url: 'http://xxx.co.uk/submit.php',
data: {
coachName: $scope.form.program.coachName,
contactArea: $scope.form.program.contractArea,
postcode: $scope.form.program.postcode,
programmeStart: $scope.form.program.programmeDate,
sessionDate: $scope.form.program.sessionDate,
sessionNumber: $scope.form.program.sessionNumber,
weekNumber: $scope.form.program.weekNumber,
id: value.participant.id,
attendance: value.participant.attendance,
weight: value.participant.weight,
goldBehaviours: value.participant.goldBehaviours,
stepCount: value.participant.stepCount,
creditData: value.participant.creditData,
weekOne: value.participant.weekOne,
stepOne: value.participant.stepOne,
weekTwo: value.participant.weekTwo,
stepTwo: value.participant.stepTwo,
weekThree: value.participant.weekThree,
stepThree: value.participant.stepThree,
weekFour: value.participant.weekFour,
stepFour: value.participant.stepFour,
weekFive: value.participant.weekFive,
stepFive: value.participant.stepFive
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data) {
//console.log(data);
});
$location.path("/thankyou");
});
Your redirect needs to be outside of your forEach.

C# with kendo ui - client send file to server

I'm trying to send a .xlsx file to my REST API using Kendo Ui. But I'm lost.
I was able to call my service, but I can't get the file. I believe I'm sending it wrong.
I don't need to save the file. I only need to read the .xlsx file to import the data to my database.
html (don't have a form):
<div>
<input name="files" id="files" type="file" />
<button id="importButton">Import</button>
</div>
js:
$("#files").kendoUpload({
async: {
autoUpload: true
},
select: onSelect
});
$("#importButton").kendoButton({
click: onImport
});
function onImport() {
var formData = new FormData();
jQuery.each(jQuery('#files')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
cache: false,
success: function (result) {
alert("Ok");
},
error: function (result) {
alert("Not Ok");
}
});
}
Server-side:
[HttpPost, Route("import")]
public void Import()
{
var streamProvider = new MultipartMemoryStreamProvider();
Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(streamProvider).ContinueWith((tsk) =>
{
foreach (HttpContent ctnt in streamProvider.Contents)
{
Stream stream = ctnt.ReadAsStreamAsync().Result;
// do something
}
});
}
Got it!
$("#files").kendoUpload({
async: {
withCredentials: false,
saveUrl: url,
autoUpload: true
},
select: onSelect
});
This answer helped me: Cross domain upload
#Brett was right, implement the kendUpload was the way.
I thought the Import button should do the magic, but I only need to use kendoUpload.
Thanks!!

Make angular-resource ignore server response

I have a resource Post, and want to be able to mark its items as read. My server only responds with status 200. This leads to angular-resource setting my Post items to ['O', 'K'].
How do I tell angular-resource to not set my post items to the server response?
var Post = $resource('/api/post/:id/:action', {
id: '#_id'
}, {
read: {
method: 'PUT',
params: {
action: 'read'
}
}
});
Post.get(function(post) {
post.$read();
}
After reading the documentation, and skimming thru the source code I didn't find any flag for this. However when using transformResponse without returning an object (e.g. angular.noop), it seems to be working.
var Post = $resource('/api/post/:id/:action', {
id: '#_id'
}, {
read: {
method: 'PUT',
params: {
action: 'read'
},
transformResponse: angular.noop
}
});

Resources