Angular.js and Node.js get a GET instead of a POST - javascript

I want to do a POST but I still have a GET on the browser.I'm using node and angular.
This is my HTML with the form.
HTML
<form ng-app="formApp" ng-controller="formCtrl">
nome:<input type="text" ng-model="nome" name="nome"><br>
cognome:<input type="text" name="cognome"><br>
ragioneSociale:<input type="text" name="regioneSociale"><br>
partitaIva:<input type="text" name="partitaIva"><br>
<input type="submit" value="Submit" ng-click="send()">
</form>
angular
this is my angular function:
<script>
var fmApp = angualr.module('formApp', []);
fmApp.controller('formCtrl', function($scope){
$scope.send = function($http){
var data = $.params(){
soggetto: JSON.stringify({
nome: $scope.nome,
cognome: $scope.cognome,
regioneSociale: $scope.regioneSociale,
partitaIva: $scope.partitaIva
});
console.log('ok');
$http({
method: "POST",
url: "/ins/sogg",
data:'data',
dataType: 'json'
}).then(function successCallback(response) {
console.log("sent")
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
// $http.post('/inserimento/soggetto', data).success function(data, status) {
// console.log('status');
})
};
};
});

Your form is submitted without ever touching the $http call, as you don't prevent defaults. Default action of a submit button is to submit the form.
Change
<input type="submit" value="Submit" ng-click="send()">
to
<input type="submit" value="Submit" ng-click="send($event)">
and
fmApp.controller('formCtrl', function($scope){
$scope.send = function($http){
to
fmApp.controller('formCtrl', function($scope, $http){
$scope.send = function(e){
e.preventDefault();

> Solved in this way
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>inserimento Dati</title>
</head>
<body>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<h1>Inserimento</h1>
<h2>Soggetto</h2>
<form ng-app="formApp" ng-controller="formCtrl">
nome:<input type="text" ng-model="nome"/><br>
cognome:<input type="text" ng-model="cognome"/><br>
ragioneSociale:<input type="text" ng-model="ragioneSociale"/><br>
partitaIva:<input type="text" ng-model="partitaIva"/><br>
<input type="button" value="Submit" ng-click="send(nome, cognome, ragioneSociale, partitaIva)"/>
Angular
<script>
var fmApp = angular.module('formApp', []);
fmApp.controller('formCtrl', function($scope, $http){
$scope.nome,
$scope.cognome,
$scope.ragioneSociale,
$scope.partitaIva,
$scope.send = function(nome, cognome, ragioneSociale, partitaIva){
var data = {
"nome": nome,
"cognome": cognome,
"ragioneSociale": ragioneSociale,
"partitaIva": partitaIva,
}; // fine JSON
var str = JSON.stringify(data);
console.log(data);
$http({
method: "POST",
url: "/ins/sogg",
data: data,
}).then(
function successCallback(response){
console.log("sent")},
function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
// $http.post('/inserimento/soggetto', data).success function(data, status) {
// console.log('status');
};
});
</script>
Server.js
app.get('/inserimento', function(req, res){
res.sendFile(__dirname + '/public/inserimento.html');
});
app.post('/ins/sogg', function(req, res){
var sog = req.body; //arriva il dato
app.use(bodyParser.json(sog));//dato in json ordinato
console.log(sog);
client.connect(function (err){
if (err) throw err;
});
var query = client.query('INSERT INTO "Soggetto" (nome, cognome, "regSociale", "partIVA") VALUES($1, $2, $3, $4)', [sog.nome, sog.cognome, sog.ragioneSociale, sog.partitaIva], function(err, result){
if(err){
console.log("Errore");
return onError(err);
}
res.writeHead(200, {'content-type': 'text/plain'});
res.end('Insert ok');
});
});

Related

Problems with ajax response in node js?

So, basically I am trying to send a request from my ajax post to my node js backend. Then I am trying to get the response back from the node js and update my view. Now, this is something that happens. Instead of just updating the resulttoken in the view, I can see in the console that whole html is loaded like a page. I am really confused. Please kindly point my error. This is what I tried so far.
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: <%=resulttoken%>;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
server
app.post("/home", function (req, res) {
var s = -1;
var t = -1;
var m = -1;
var phonenumber = req.body.phonenumber;
var review = req.body.review;
console.log(phonenumber);
fd.insertreview(phonenumber,review).then(function(v) {
if(v=="1") {
console.log("Your review has been inserted successfully");
s = md.getRand();
console.log("Unique number is",s);
fd.checkifuniquenumberexists(s).then(function(u){
if(u!="1"){
console.log("Unique number doesnt exist");
fd.inserttoken(s,phonenumber).then(function (p) {
if(p=="1"){
console.log("Token has been inserted successfully");
res.render('trial',{"resulttoken":s});
}
})
}
});
}
});
});
This is what loads on the console log
info <!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: 35055;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
The issue is this line
res.render('trial',{"resulttoken":s});
You're returning the entire page as your response, if you just need the token you can return this as part of a JSON response e.g.
res.status(200).json({ token: s });
then at the client
$.post('/home', { phonenumber, review }, res => {
// use res.token
console.log(`Token: ${res.token}`);
})
.fail(console.error);

Refresh/ Re Render the UI once Submit button is clicked

Currently I am using AnularJS to update the value from JSON file and Once I click Submit button , I want to clear the whole DOM and refresh the UI and update the contents. Can you please help here
Here Value1 and Value2 comes from two different functions but sometimes . Value2 will be null and only Value1 will be present. but still Value2 will be shown with Old value and Value1 with updated value after clicking submit button.
Is there any way in AngularJS to refresh the DOM before updating the values. so that once i click submit i should be seeing only Value1
var app = angular.module('myApp', ['angular-loading-bar']);
app.controller("Controller", ["$scope", "$http", "$window",
function ($scope, $http, $window) {
$scope.firstFunction = function () {
$http({
method: 'POST',
url: 'one.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"accountnumber": $scope.accountnumber,
"environment": $scope.selectedVal,
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.value1 = response.data
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
$scope.secondFunction = function () {
$http({
method: 'POST',
url: 'two.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"accountnumber": $scope.accountnumber,
"environment": $scope.selectedVal,
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.value2 = response.data
console.log($scope.cellularIPAddressValue);
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body ng-app="myApp">
<div ng-controller="Controller">
<div class="row">
<div class="input-group form-search">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="firstFunction();secondFunction();" class="btn btn-primary">Submit</button>
</span>
<span id="message">{{value1}}</span>
<span id="message">{{value2}}</span>
</div>
</div>
</div>
</body>
</html>
There is no need to refresh UI as angular data-binding does the job.
Changing the ng-click="firstFunction();secondFunction();"
to ng-click="value1=null;value2=null;firstFunction();secondFunction();" may help.

AngularJS: Call httpget on value change from textbox

I have a web service which returns json file on call with a parameter for the id of an entry. I have a angular method that returns the data returned from that method. I have no idea how to recall the service when the input of the id has changed as I want to recall that method when a new value has been supplied.
The parameter that I pass in for the Id is called Reference. The HTML returns object with a reference of 1234 but if I change the value I dont know how to recall the service.
This is what I have so far:
Angular:
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : '1234' }
})
.then(function (response) {
$scope.booking = response.data
});
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
Html
<!DOCTYPE html>
<html>
<head>
<script src="scripts/angular.js"></script>
<script src="app/NewAppTwo.js"></script>
</head>
<body ng-app="myModule" ng-controller="myController">
{{test}}
{{Reference}}
<br />
<br />
<input type="text" ng-model="Reference" ng-change="booking"/>
{{booking}}
</body>
</html>
Change ng-change="booking" to a function that is called everytime that models Refences changes:
$scope.getReference = function(referenceNumber){
$http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : referenceNumber}
}).function (response) {
$scope.booking = response.data
});
}
<input type="text" ng-model="Reference" ng-change="getReference(Reference)"/>
try this :
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
$scope.refresh = function(){
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : $scope.Reference }
})
.then(function (response) {
$scope.booking = response.data
});
}
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
and html
<input type="text" ng-model="Reference" ng-change="refresh()"/>
ng-change call the given function each time the input change.
refresh() don't need a parameter because it use $scope.Reference

Trouble in authorization with post request in Angular

I have a some problem with authorization in my app. I realize it through factory and controller, post method send request, but in response i have log from server, that values are wrong.
But if I change body of doLogin function to jQuery ajax method and don't use factory, all is OK. What is wrong with my Angular way?
My AngularJS Code
Form:
<form ng-submit="doLogin(credentials)">
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" ng-model="credentials.email">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="credentials.password">
</label>
<label class="item">
<button class="button button-block button-positive" type="submit">Log in</button>
</label>
</div>
</form>
Factory:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
console.log('service');
console.log(credentials);
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: credentials,
async : true
}).success(callback);
}}})
Login function in controller:
$scope.doLogin = function(credentials) {
var successCallback = function (data) {
console.log(data);
}
Somepost.doPost(credentials, function(data) {
console.log(data);
});
};
Function doLogin with $.ajax (working successfully):
$scope.doLogin = function(credentials) {
var successCallback = function (data) {
console.log(data);
}
var login = function(credentials, successCallback) {
$.ajax({
type: "POST",
url: 'http://cronicls.ru/auth/login',
async : true,
data: credentials,
success: function(data){
console.log('login success');
console.log(data);
successCallback();
},
error: function(data){
console.log('/auth/login: error');
console.log(data);
}
});
};
login(credentials, successCallback);
};
but in response i have log from server, that values are wrong.
Actually not, because it returns a promise and you have to do something like this in your callback:
As per your comment :
It's PHP with ZF on server side. Actually you need to change the default content Type header from application/json to application/x-www-form-urlencoded
Change in factory:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
console.log('service');
console.log(credentials);
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: credentials,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}, // <-- override the default contentType header
async : true
}).then(callback); // change to then instead of success
}}})
I found the answer of my problem. Thanks to #Jai for hint about ZF. Actually we need to wrap data in $.param(). So, working factory is:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: $.param(credentials),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(callback);
}
}
})

How to submit a straightforward form using Angular

Using angular, I want to submit a form and store the response. My code looks something like this:
<form ng-controller="myController" action="myAction" method="POST">
<input type="text" name="name" />
<input type="submit" ng-click="submit" />
</form>
<script>
function myController($scope, $http) {
$scope.submit = function() {
$http.post(url, data).success(function(data) {
$scope.result = data;
});
}
}
</script>
How do I get url and data to be the form action and inputs, respectively? I don't want to send JSON, I want the server side to see this is a regular HTML form submit.
Thank, #Vincent Ramdhanie, for pointing me in the right direction. Here's what I ultimately did, using plenty of jQuery thrown in:
function myController($scope, $http) {
$('form').submit(function() {
return false;
});
$scope.submit = function() {
form = $('form');
data = form.serialize();
url = form.attr('action')
$http.post(url, data,
{ headers:
{ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data) {
$scope.result = data;
}
);
}
}
This is how I accomplish this, start by binding the form data to your model, Then use a transform to transform your JSON data into regular post parameters. This solution depends on the jQuery param() function:
<form ng-controller="myController" method="POST">
<input type="text" name="name" ng-model="name"/>
<input type="submit" ng-click="submit" />
</form>
function myController($scope, $http) {
$scope.name = "";
/* Helper function to transform the form post to a regular post rather than JSON */
var transform = function(data) {
return $.param(data);
}
$scope.submit = function() {
$http.post('myAction', $scope.name, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transform
})
.success(function (data) {
$scope.result = data;
});
}
}

Categories