I am buiding a CRUD apps with AngularJS and Django REST API.
I have created get and post method successfully but not getting how to put request. i tried stackoverflow lots of problem and youtube but i couldnt sort it out.
my current controller is:
app.controller('crudCtrl', function($scope, $http) {
$http.get("http://127.0.0.1:8000/api/v1/contact/?format=json")
.then(function(response) {
$scope.contacts = response.data; //this is get method that displayed all the list of contact
});
$scope.formModel = {}; // this is same input.js, it is POST method to to send data to database
$scope.onSubmit = function () {
console.log("hey, i am submitting");
console.log($scope.formModel);
$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel).
success(function (data) {
console.log(":)");
}).error(function (data) {
console.log(":(");
});
};
$scope.selectUser = function (contact) {
console.log(contact); // it will select the data exactly where you click
$scope.clickedUser = contact;
};
$scope.updateUser = function (argument) { // it will get the form editable exactly which contact you clicked
};
});
and my edit view is, when i click on edit buttion, the form will be appear:
<form>
<input type="text" ng-model="clickedUser.userid">
<input type="text" ng-model="clickedUser.name">
<input type="text" ng-model="clickedUser.email">
<input type="text" ng-model="clickedUser.phone">
<button type="submit" ng-click="updateUser()" data-dismiss="modal">Submit</button>
</form>
Point to be noted, the edit form working nice on client side but it doesnt send the data to backend/API/Database.
can anyone tell me how can i do $http.put request? i tried w3school, youtube, and stackoverflow problem.
i got huge solution but i couldnt solve it.
this is my api endpoint for anything: http://127.0.0.1:8000/api/v1/contact/ so if i want to update particular field, i have to go through this url: http://127.0.0.1:8000/api/v1/contact/1 in the end of the url is id
I hope it is clear to you
You can try this as well
$http({method: "PUT", url: URL}).
then(
function(response) {
}, function(response) {
});
Can you just use angular put?
See: https://docs.angularjs.org/api/ng/service/$http#put
var clientData = {
text: "Put this somewhere"
};
$http.put( url, clientData ).then( function( serverResponse ) {
console.log(serverResponse);
},( error )=>{
console.log(serverError);
});
Related
I'm building a simple auction site. I showed my products in the page. Now i wanna make a new offer. in my controller i use ng-dialog to open a pop-up form and i pass inside the auction that i need. like this:
$scope.clickToOpen4 = function (followingauction) {
console.log(followingauction.allbids[followingauction.allbids.length -1].bid);
var newScope = $scope.$new();
newScope.auction = followingauction;
ngDialog.open({template: '../views/partials/offer.html',
className: 'ngdialog-theme-default',
scope: newScope
});
};
In my template offer.html i have a simple form:
<form name="Offer" ng-controller="FollowingAuctionsController">
Your Offer:<br>
<input type="number" placeholder="Your Offer" ng-model="newOffer" name="new offer" required> €<br>
<input class="btn" type="submit" ng-click="submitNewOffer(auction._id, auction.allbids[auction.allbids.length -1].bid)" value="OK"><br>
And in the submitNewOffer i pass, the id of the auction and the highest offer.
And this is the submitnewOffer():
$scope.submitNewOffer = function (id, bid) {
console.log(id);
console.log(bid);
var newBid = $scope.newOffer;
if (newBid>bid) {
console.log(newBid);
console.log('/api/followingauctions/newoffer/' + id);
$http.put('/api/followingauctions/newoffer/' + id, newBid)
.then(function () {
alert('Offert Done!');
getFollowingAuctions();
});
}
else {
alert('The offer must be higher!');
$scope.newOffer = '';
}
};
Like you see i do the console.log to see if the data that i passed into the template are ok. They are!
Than if the new bid is less than the highest bid that i passed, i send that alert, else i put the new offer.
All works fine and all the console.log are fine. But when i submit the newBid (that is higher than the old bid) it send me this error:
angular.js:12578 PUT http://localhost:3001/api/followingauctions/newoffer/58dbd190b8042b080d1418bf 400 (Bad Request)
angular.js:14516 Possibly unhandled rejection: {"data":"Unexpected token 8400SyntaxError: Unexpected token 8\n at parse (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/types/json.js:83:15)\n at /Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/read.js:116:18\n at invokeCallback (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:262:16)\n at done (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:251:7)\n at IncomingMessage.onEnd (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:307:7)\n at emitNone (events.js:86:13)\n at IncomingMessage.emit (events.js:185:7)\n at endReadableNT (_stream_readable.js:974:12)\n at _combinedTickCallback (internal/process/next_tick.js:74:11)\n at process._tickCallback (internal/process/next_tick.js:98:9)","status":400,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/followingauctions/newoffer/58dbd190b8042b080d1418bf","data":800,"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request"}
You are using the method incorrectly.
The right signature of $http.put method is put(url, data, [config]);
So, your code could look like this:
$http.put('/api/followingauctions/newoffer/' + id, {newBid: newBid})
.then(function () {
// success
});
and you can access newBid from POST at the backend
OR
$http.put('/api/followingauctions/newoffer/' + id, {}, {params: {newBid: newBid}})
.then(function () {
// success
});
in which case, newBid can be obtained from GET at the backend
When doing a PUT request with $http, you have to specify the params:
$http.put('/api/followingauctions/newoffer/' + id, {}, params: {'newBid': newBid})
.then(function () {
alert('Offert Done!');
getFollowingAuctions();
});
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
trying to send $http.post request from AngularJS form to Symfony controller to add form content to database. I can get success response with "status": 200 at AngularJS side.
However, at Symfony controller, $request->getContent() is empty, returns nothing; $request->getMethod() returns 'GET', which doesn't make sence to me. How can I get post data in Symfony??
P.S. Installed FOSRestBundle and enabled body listener, param fetcher listener.
I know my question is duplicated with POST Ajax request by AngularJS to Symfony controller, but 2 answers of this post didn't work for me.
My blog.html.twig,
<form name="replyForm" ng-submit="sendReply(blog.id)">
Preview: {{'{{reply.content}}'}} <br><br>
My Reply: <input type="text" name="content" ng-model="reply.content" />
<input type="submit" value="Reply" />
</form>
blog.js,
$scope.reply = {};
$scope.sendReply = function(blogId){
$scope.reply.blog = blogId;
$http.post('http://localhost/app_dev.php/blogReply', $scope.reply, {'Content-Type': 'application/x-www-form-urlencoded'})
.then(function(data){
$scope.message = angular.fromJson(data);
}, function(data){
$scope.message = angular.fromJson(data) || "Request failed";
});
$scope.reply = {};
}
Symfony blogController,
/**
* #Route("/blogReply", name="blogReply")
*/
public function replyAction(Request $request){
$data = $request->request->get('data', 'default value if data does not exist');
return new Response ($data);
}
The result is 'default value if data does not exist'.
When I try to change the status of a blog , the status is not updating in database. Status is string field and is initially stored as 0 in database
api.post('/statuschange', function(req, res){
Blog.find({_id: req.query.blog_id}).update({$set:{'status': req.body.status}}, function (err, status) {
if(err){
res.send(err);
return;
}
if(req.body.status == '1') {
res.json('Blog added')
return;
}
if(req.body.status == '-1'){
res.json('Blog not added');
return;
}
});
})
api is working successfully on postman
factory file
angular.module('blogfact', ['authService'])
.factory('blogFactory', function($http, AuthToken){
var factory = {};
var token = AuthToken.getToken();
factory.changestatus = function(info, callback){
$http({
url: 'api/statuschange',
method:'POST',
headers:{'x-access-token':token},
params:{'blog_id': info},
})
.success(function(response){
callback(response)
})
}
return factory
})
the controller file
angular.module('blogCtrl', ['blogfact']);
.controller('BlogController', function(blogFactory, $routeParams){
var that=this;
blogid = $routeParams.id;
var getthatBlog = function(){
blogFactory.getthatBlog(blogid, function(data){
//console.log('[CONTROLLER] That Blog:',data);
that.blog = data;
})
}
this.changestatus = function(info){
blogFactory.changestatus(info, function(data){
getthatBlog();
})
}
})
html file
<div ng-controller="BlogController as blog">
<textarea ng-model="blog.status"></textarea>
<button class="btn btn-success" ng-click="blog.changestatus(blog._id)">Submit</button>
</div>
If your question is regarding the value in MongoDB not being updated, well it seams it is due to the status data missing in your POST request.
I recommend that in your HTML, send the whole blog object so that you have the blog's status as well:
<button class="btn btn-success" ng-click="blog.changestatus(blog)">Submit</button>
Then in your blogFactory add the data as such:
$http({
url: 'api/statuschange',
method:'POST',
headers:{'x-access-token':token},
params:{'blog_id': info._id},
data: {status: info.status} // <==
})
Now, you should be able get the blog status data in NodeJS server back-end via req.body.status.
Update
Try the following with mongoose's update method:
Blog.update({_id: req.query.blog_id}, {status: req.body.status}, function(err, numAffected){
...
});
Or, alternatively:
Blog.findOne({_id: req.query.blog_id}, function(err, blog){
blog.status = req.body.status;
blog.save();
});
Angular let's you modify collection data on the client-side, but to actually update it on your server you need to notify the server of your changes (via API).
There are a few ways to do this, but if you want seamless updating from client-side to server maybe give meteor a try.
http://www.angular-meteor.com/
https://www.meteor.com/
Your are sending the data in params and getting the data from req.body.
You should use req.query or req.param. Else, Send the data on body like below,
$http({
url: 'api/statuschange',
method: 'POST',
params: { 'blog_id': info },
data: { 'status': 1 }
})
Your are passing 1 parameter in client side and getting two parameters on server side(req.body.status, req.query.blog_id)
Where is the token value from ?
Check the simplified way to test your code
http://plnkr.co/edit/tyFDpXw2i0poICwt0ce0
I am doing options request data from server by using Nodejs,
but I don't know how to handle response data with delay in same request,
Here's the front code:
HTML(click to request data from server):
<div ng-controller="testCtrl">
<label>
<input type="radio" ng-model="animalSpecies.species" ng-click="selectAnimal()" name="animal" value="Dog"/>Dog
</label>
<label>
<input type="radio" ng-model="animalSpecies.species" ng-click="selectAnimal()" name="animal" value="Cat"/>Cat
</label>
Angular:
function testCtrl($scope, $http) {
var config;
$scope.animalSpecies = {
species: ""
}
$scope.selectAnimal = function () {
config = {
method: "GET",
url: "/getanimal",
params: {
species: $scope.animalSpecies.species
}
}
$http(config).then(
function (res) {
console.log(res.data);
}
)
}
}
Nodejs
app.get("/getanimal", function (req, res) {
var species = req.query.species;
if (species === "Dog") {
setTimeout(function () {
res.send({msg: "species is" + species});
}, 1000)
} else {
res.send({msg: "species is" + species});
}
})
When you click "Dog" option first and quickly click "Cat" option,
the "Cat"'s response data will first come out ,but finally the "Dog"'s
data will response a second later.(I do a setTimeout delay in Nodejs,but maybe
other conditions like querying database callback delay or somehow)
What I want is just:Is there some way to stop server to response data or
I get what I want doing in frontend?
Best way is to disable the control for the user if the first response hasn't come back yet.
Disable the input buttons when the user clicks one of them, and enable them on server response