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">
Related
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);
});
Here I use codeigniter and AngularJS....
What's wrong with my code?
That I want, I want to retrieve its data from 'input text'.
And I only get empty data when doing 'console.log()'
in index.html
<input type="text" ng-model="search_data">
<span class="display-ib" ng-click="testGetDataSearch()"></span>
in app.js
$scope.testGetDataSearch = function()
{
$http({
method: 'GET',
url: 'home/naonwelah',
data: { 'valSearch': $scope.search_data }
}).then(function (success){
console.log(success.data);
},function (error){
console.log(error);
});
}
in AjaxRequest.php
public function naonwelah()
{
if ( isset($_GET['valSearch'])) {
$searchValue = $_GET['valSearch'];
$result = $this->dbxs7h3j9213m02147ca_model->cariBrow($searchValue);
var_dump($result);
}
}
It's Very Simple, Change 'data:' to 'params:', and Try This :)
$scope.testGetDataSearch = function()
{
$http({
method: 'GET',
url: 'home/naonwelah',
params: { 'valSearch': $scope.search_data }
}).then(function (data){
console.log(data);
},function (error){
console.log(error);
});
}
What happens if you open the search-url directly? Do you get any output? Have you inspected the request in the ChromeDevTools? That might also help to narrow the problem down.
One issue however might be that var_dump produces no valid JSON.
I'm playing around with a twitter API wrapper for Node right now and am trying to figure out how to pass a query parameter from an HTML form to an AJAX get request and have that parameter then passed into my Express route, rather than just having the form action go directly to the route.
Here's my HTML code
<form id="searchTerm">
Keyword:<input id="keyword" type="text" name="q" placeholder="Keyword">
<input type="submit">
</form>
My client-side Javascript
$(document).ready(function() {
$('#searchTerm').on('submit', function() {
$.ajax({
type: 'GET',
data: q,
url: '/search/tweets/term',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
And then my Node.JS route:
// Search by keywords or phrases
app.get('/search/tweets/term', function(req, res) {
var q = req.query.q;
// Accesses the Twitter API and pulls back the respective tweets
client.get('search/tweets', {q: q, count: 100, lang: 'en', exclude: 'retweets'}, function(error, tweets, response) {
if(!error) {
res.send(tweets);
} else {
console.log(error);
res.status(500).send(error.stack);
}
});
});
I'm getting a "Query Missing Parameters" error message in my terminal whenever I input a value into the form, however. Not sure what I'm doing wrong.
UPDATE
Got it working via the following:
$(document).ready(function() {
$('#searchTerm').on('submit', function(e) {
e.preventDefault();
var q = $('#keyword').val();
$.ajax({
type: 'GET',
data: {q: q},
url: '/search/tweets/term',
success: function(data) {
console.log(data);
}
})
})
})
However, since I'm implementing e.preventDefault(), I'm losing the query parameters within my URL. Since I want to give users the ability to share URL's to specific keywords, is there any way to be able to keep these parameters intact in the URL while still getting the JSON sent client side? Or will have to just manipulate the JSON on the server side and have the data be rendered in via a template engine?
Try this
$(document).ready(function() {
$('#searchTerm').on('submit', function() {
$.ajax({
type: 'GET',
data: q,
url: '/search/tweets/term?q=',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
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
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);