How to pass GET response data to POST Request - javascript

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
}
});
}

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);
});

Angular form not submitting via post

Please check why this angular code does not submit url via post. I am trying to send my form details through sms, to post a request via mobile.
<div id="page7-container1" ng-app="amApp">
<h4 id="page7-heading1" style="color:#000000;">App</h4>
<div id="page7-markdown3" class="show-list-numbers-and-dots">
</div>
<div id="page7-markdown6" class="show-list-numbers-and-dots">
</div>
<div id="page7-markdown5" class="show-list-numbers-and-dots">
</div>
<div id="page7-markdown4" class="show-list-numbers-and-dots">
</div>
<h3 id="page7-heading4" style="color:#337AE2;font-weight:600;">Request a call back</h3>
<form id="page7-form2" class="list" ng-controller="formCtrl" ng-submit="submitForm()">
<label class="item item-input item-floating-label" id="page7-input0">
<input type="text" name="formAdata.rname" required placeholder="Enter Your Name">
</label>
<label class="item item-input item-floating-label" id="page7-input1">
<input type="number" name="formAdata.rmobile" required placeholder="Enter Mobile Number">
</label>
<label class="item item-input item-floating-label" id="page7-input2">
<input type="text" name="formAdata.rlocation" required placeholder="Enter Your location/district/state?">
</label>
<input id="page7-button12" type="submit" ngClick="Submit" class="button button-positive button-block" value="Request call back!">
</form>
<script language="javascript">
var messager = '';
var app = angular.module('amApp', []);
app.controller('formCtrl', function ($scope, $http) {
$scope.submitForm = function() {
messager = "http://amritamultimedia.co.in/sms/sendsms.php?uid=9947009540&pwd=A3228B&msg=I am "+$scope.formAdata.rName+" from "+$scope.formAdata.rLocation+". My mobile number is: "+$scope.formAdata.rMobile+", I would like to get more info about Courses. Requested call back from your Mobile App, Please call me to my mobile.";
$http({
url: messager,
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.formAdata)
}).success(function(data, status, headers, config) {
document.getElementById("page7-form2").innerHTML = "We will get back to you within 3-4 hours. Thanks for checking our app.";
}).error(function(data, status, headers, config) {
});
};
});
</script>
</div>
What must be missing, or what am doing wrong?
Please help!
Thanks,
Sj
add this to your controller
$scope.formAdata={};
your using json parameters, so your formAdata doesn't gets binded properly.
Also check you are using POST but passing the data like a query string, so need to bindand send as a json object or use GET method.
One more thing double check if the value of messenger is getting assigned or not since there is no datatype is mentioned
var app = angular.module('amApp', []);
app.controller('formCtrl', function ($scope, $http) {
$scope.formAdata={};
var messager = "";
$scope.submitForm = function() {
messager = "http://amritamultimedia.co.in/sms/sendsms.php;
var userData={
"uid":mobilenumber,
"pwd":password,
"phone":$scope.formAdata.phone,
"msg": $scope.formAdata.message
}
$http({
url: messager,
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: userData,
}).success(function(data, status, headers, config) {
document.getElementById("page7-form2").innerHTML = "We will get back to you within 3-4 hours. Thanks for checking our app.";
}).error(function(data, status, headers, config) {
});
};
});
This will work.

Input field should not clear after submit using angularjs

HTML
<form ng-controller="updatecontroller" ng-submit="updateUser()"><label class="control-label">First Name</label>
<input type="text" ng-model="user.userFirstName">
<label class="control-label">Last Name</label>
<input type="text" ng-model="user.userLastName" ><button type="submit" ng-click="updateUser()">Update</button>
</form>
JS
app.controller('updatecontroller', function ($scope, $http, $cookieStore) {
$http.get('http://localhost:8080/myapp/user/'.concat($scope.getUserId) + '?access_token=' + $cookieStore.get("access_token")).
then(function (response) {
$scope.user = response.data;
});$scope.user = {"id": "","userFirstName": "","userLastName": ""}
$scope.updateUser = function () {
var url = "http://localhost:8080/myapp/user/".concat($scope.getUserId) + "?access_token=" + $cookieStore.get("access_token");
var method = "PUT";
$http({
method: method,
url: url,
data: angular.toJson($scope.user),
headers: {
'Content-Type': 'application/json'
}
})
};});
values will appear in text field. i have to update. the values are getting updated in database. but what i want is.. the updated values should not clear after submit the form.
Thanks!
You can empty the input filed after get the response from HTTP request
$scope.updateUser = function () {
$http({
method: 'POST',
url: 'myUri',
data: 'your data'
headers:'header'
}).then(
function(res) {
$scope.user = {"id": "","userFirstName": "","userLastName": ""} //clear the input field here
},
function(err) {
}
);
}
Place your Submit Button inside the Form Element then try it it will clear the input after the submission.
your updateUser() method seems to be the problem. It's probably clearing user.userFirstName & user.userLastName (or the whole user)
please show us what updateUser() is doing to be sure

AngularJS Does not send HTTP Post request

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);

How can I use Angular $http to POST data to PHP

plenty of topics regarding this and I promise I have tried a lot (all day).
Here is the code I have:
app.controller('contactsController', function($scope, $rootScope, dataService, $http) {
$rootScope.currentPage = "contact";
$scope.postData = [];
$scope.runScript = function() {
$http({
url: "post.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({postData:$scope.postData})
}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
};
});
<form name="contactForm" method="post" ng-submit="runScript()">
<div class="col-sm-10">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">E-mail Address</span>
<input ng-model="{{postData.email}}" name="email" class="form-control" placeholder="johnsmith#example.com" aria-describedby="basic-addon1" required>
</div>
<br>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Message</span>
<textarea ng-model="{{postData.message}}" name="inputMessage" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-default">Send</button>
</div>
</form>
{{data}} and {{status}}
$inputData = file_get_contents("php://input");
$inputData = json_decode($inputData);
$email = $inputData->email;
echo $email;
Now I've probably made a few mistakes whilst trying to get this to work, from what I had earlier - I'm not getting any errors but I'm also not getting any success - I've been at this all day!!!! Thanks!
Angular posts the data in JSON format that php does not natively consumes. You will have to read and json decode the input like so:
// get the raw POST data
$inputData = file_get_contents("php://input");
// this returns null if not valid json
$inputData = json_decode($inputData);
I might be wrong but if you only use POST you should find your data in the _POST variable. You need to use file_get_contents("php://input") only if you submit PUT requests.
Also, you are submitting a key postData and you are trying to read ->email..

Categories