AngularJS Does not send HTTP Post request - javascript

I have following code:
application.controller('userLoginController', function($scope,$http){
window.document.title = "User Login";
$scope.form = { username: '',password: ''};
$scope.submitLogin = function(){
var config = {
method: 'POST',
url: 'server_app/login.php',
data: {
'username' : $scope.form.password,
'password' : $scope.form.password
}
};
var request = $http(config);
request.then(function (response){
$scope.errorMessage = response.data;
},function(error){
$scope.errorMessage = error.data;
})
}
});
I was trying to send POST request to backend server which look like that:
var_dump($_POST);
After submitting my data with a button I should get array with $_POST back.
Insteed of that I get
array (size=0)
empty
My HTML code look like that:
<input placeholder="Login" class="searchProduct" autocomplete="off" name="username" type="text" ng-model="form.username"><br>
<input placeholder="Password" class="searchProduct" autocomplete="off" type="password" name="password" ng-model="form.password"/>
<div class="button" ng-click="submitLogin();">Login</div>
I don't see any problem here..

I hope you are receiving data as below in php file as angular code seems to be fine .
$params = json_decode(file_get_contents('php://input'),true);

You can use the below code
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

Related

Converting to string NodeJS Express http response returns in AngularJS

I am trying to build an angularjs program which talks to express / nodejs api and mysql database.
In login page , I am able to call the api correctly and it connects with mysql and based on right combination of user name and password , I am sending back "password matches" or "failure".
When I am accessing that on HTML using $scope , I am getting ["password matches"] and not password matches . I have tried toString, splice, etc but no proper result.
Controller
var passStats=[];
passStats = LoginFactory.validateUserLoginFactory(uName, pWD)
$scope.pwdStatus = passStats;
Factory
app.factory("LoginFactory", function ($http) {
var factory = {};
factory.validateUserLoginFactory = function (UserName, PWD) {
$http({ method: "POST", url: 'http://localhost:3000/validateUserLogin/', data: { limit: userForm }, cache: false }).then(function (response) {
StatusPWD.push(response.data);
}, function (error) { console.log(error); });
return StatusPWD;
}
return factory;
});
node.js
res.send('password matches');
HTML
<label>User Name</label>
<input type="text" ng-model="enteredUserName" class="w3-input w3-border w3-padding">
<br>
<label>Password</label>
<input type="text" ng-model="enteredPWD" class="w3-input w3-border w3-padding">
<br>
<input type="button" ng-Click="validateLogin(enteredUserName,enteredPWD)" value="Login" class="w3-btn w3-padding w3-green">
<br> <br> <br>
<label>password {{ pwdStatus}}</label>
It is because you are using StatusPWD.push which is pushing it into an array.
the passStats variable is an array, where you are pushing the response.
you can simply do this to get the value if passStats is an array
$scope.pwdStatus = passStats[0]
or you can do
$scope.pwdStatus = passStats.join("")
I have solved my problem for which I posted the question. I had coded the factory and controller part wrongly. Following modification is giving me proper out put in HTML
Factory
factory.validateUserLoginFactory = function (UserName, PWD) {
var userForm = {};
userForm = { user: UserName, password: PWD };
return $http({ method: "POST", url: 'http://localhost:3000/validateUserLogin/', data: { limit: userForm }, cache: false });
}
Controller
$scope.pwdStatus;
LoginFactory.validateUserLoginFactory(uName, pWD)
.then(function (data) {
console.log(data.data);
$scope.pwdStatus = data.data;
}, function (data) {
console.log(data);
});

How to pass GET response data to POST Request

I am new using Angularjs and I am having an issue while parsing a JSON response. I am doing client side authentication for the login page and I have used get request to fetch data from servers side and post request for client side.
HTML code :
<form ng-submit="loginform(logcred)" class="ng-scope ng-pristine ng-valid center" name="logform"><br/><br>
<tr ng-repeat="logcred in serverinfo"></tr>
<div>
<label form="emailinput"><b>Email</b></label>
<input type="email" class="form-control" name="uname" id="emailinput" placeholder="you#example.com" ng-model="logcred.username" >
</div>
<div>
<label form="pwdinput"><b>Password</b></label>
<input type="password" class="form-control" name="pwd" id="pwdinput" placeholder="*******" ng-model="logcred.password">
</div>
<div>
<button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
<button class="btn btn-primary" ng-click="submit()">Login</button>
</div>
<br/>
</form>
AngularJS code :
var myApp = angular.module('myApp', []);
myApp.controller('credientials', function($scope, $http) {
/* server side response*/
$http.get('http://localhost:3000/loginfo
.then(
function successCallback(response){
$scope.serverinfo = response.data;
});
/* client-side response*/
$scope.loginform = function(serverinfo,username,password){
$http({
url: 'http://localhost:3000/loginfo',
method: 'POST',
data: {
"username" :username,
"password" :password,
}
})
.then(
function successCallback(response){
console.log(response);
if (serverinfo.username === response.data.username && serverinfo.password === response.data.password) {
$scope.signinfo = response.data;
}else{
console.log("Error: " + response)
}
});
}
Problem what I am facing is, I need to send the GET response data into POST request and there I am doing the condition check, if the username and password matches, it's should give success meassage. But I am not sure my thinking is right or not.
What am I doing wrong?
Any help / advice would be greatly appreciated.
You can try below code.
$scope.loginform = function(serverinfo,username,password){
$http({
url: 'http://localhost:3000/loginfo',
method: 'POST',
data: {
"username" :username,
"password" :password,
}
})
.then(
function successCallback(response){
console.log(response);
if (response) { // Response will be either true or false. For this yu need to change the API response.
//Logged in successfully
}else{
//Something went wrong
}
});
}

Get input field through javascript and use variable in php?

The question says it all.
Any ideas?
HTML
<input type="text" name="username" class="form-control search-query" placeholder="Enter User Name">
JavaScript
$http({
method: 'POST',
url: 'url.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
"username": $scope.username,
},
}).then(function (response) {
var data = response.data;
}
PHP
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$accountnumber = $request->accountnumber;
It's not $post_"username". You should use $_POST["username"]; to get post parameters from the sever php script.

angularjs http post method

Trying to post something back to the mongodb however its not sending anything, when I click submit its passing {} back to the cmd and the network console is hanging on pending then it will fail when its taking long to post.
Can someone shed a light on this one please, thanks.
Html:
<input type="text" ng-model="vm.user">
<input type="text" ng-model="vm.pass">
Service:
function _postUser(user,pass){
var params = {
user: user,
pass:pass
}
return $http({
method: 'POST',
url: '/loginDB',
params: params
})
}
Get users: I get the users from the DB.
vm.getUsers = function (){
homeService.getUsers()
.then(function(response){
vm.users = response.data;
console.log(vm.users);
});
}
Post action:
vm.postUser = function() {
// console.log('send it back')
homeService.postUser(vm.user)
.then(function(response){
console.log('send it back')
})
}
Server.js app.post back to db
app.post('/loginDB', function (req, res){
console.log(req.body);
});
Edit: its posting but now taking the ng-model, I know something is wrong with the ng-model but just can't get my head on it.
db.loginDB.insert(req.body, function(err, doc){
res.json(doc);
})
Try changing params key to data
return $http({
method: 'POST',
url: '/loginDB',
data: params
})
In the html too you have the same model for both the inputs,
controller declaration,
vm.newuser = {user:'',pass:''};
html
<input type="text" ng-model="vm.newuser.user">
<input type="text" ng-model="vm.newuser.pass">

AJAX call to rest service to post the data from HTML form

<html>
<body>
<form method="POST">
<label>username</lable>
<input id="username" name="username" type="text">
<label>emailid</lable>
<input id="emailid" name="emailid" type="text">
<button id="enter" type="submit">submit</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
var userName = $("#username").val();
var emailId = $("#emailid").val();
$($enter).click(function () {
$.ajax({
type: 'POST',
url: ".....rest service url....",
dataType: JSON,
data: {
"UserName": userName,
"EmailId": emailId
},
success: function (data) {
alert("success");
}
error: function (e) {
alert("error" + e)
}
});
});
});
</script>
</body>
</html>
I'm trying to post the form field in rest service which expects a JSON response.
I'm getting an alert error message (object Object)
I'm not getting where the error is.
You can try $.post instead of $.ajax
$.post( "your url",{ UserName: userName, EmailId: emailId }, function( data ){
alert("Success");
});
Just make sure that parameters you are passing matches with your REST service.
$($enter).click(function () {
this part of code looks invalid, provide a correct selector to the click function.
First change this
$($enter).click(function to
$("#enter").click(function () {
Are you sure the the service you written for this task is a post service...some times i do the mistake like post data and write service for getting data.If you can show your service structure it will help to have a better insight.

Categories