AngularJs post request getting error - javascript

I am trying to do a POST request to a login api through angular js .
<form method="post" ng-submit="doLogin()">
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" ng-model="loginData.user_mail">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="loginData.password">
</label>
<label class="item">
<button class="button button-block button-positive" type="submit" >{{loginTxt}}</button>
</label>
</div>
</form>
Controller.js
$scope.doLogin=function(){
$http({
method : 'POST',
url : 'http://examplemns.com/customer/api/v1/login/login',
data : $scope.loginData, //forms user object
timeout:20000
})
.success(function(response){
alert(JSON.stringify(response));
})
.error(function(err){
console.log(JSON.stringify(err));
alert("Network error");
});
}
But i will get invalid username response even if the username and password is correct.
I checked the api through postman plugin its working fine,but when comes with angular i will get invalid.
Here is the sample input
user_mail:avm#gmail.com
password:123456
When try this input with postman plugin i will get the correct response
{
"status": 1,
"message": "Done",
"data": {
"name": "A.V.M TOURIST HOME",
"username": "avm#gmail.com",
"id": "37",
"key": "cos4ok88woo0kcw40cog0s4gg4skogscso8848ok"
}
}
but when trying through the angularjs post i with the same input i will get this response
{"status":0,"message":"Invalid username"}
Please help me:(
UPDATE
I need to transform my data to application/x-www-form-urlencoded rather than json (from comments) for that i am used this way.
var data= {user_mail:$scope.loginData.user_mail,password:$scope.loginData.password};
$http({
method : 'POST',
url : 'http://examplemns.com/customer/api/v1/login/login',
data : data,
timeout:20000
})
.success(function(response){
alert(JSON.stringify(response));
})
.error(function(err){
console.log(JSON.stringify(err));
alert("Network error");
});
But again i will get the same
Screenshot of request and response from the postman

Try this
$scope.loginData = {};
$scope.doLogin=function(){
$http({
method : 'POST',
url : 'http://examplemns.com/customer/api/v1/login/login',
data : $scope.loginData, //forms user object ,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response){
console.log(response);
})
.error(function(err){
console.log(err);
});
}
OR
$scope.loginData = {};
var data = $scope.loginData;
$http.post('/examplemns.com/customer/api/v1/login/login', data).then(successCallback, errorCallback);
ALSO TRY THIS
<input type="text" ng-model="user_mail">
<input type="password" ng-model="password">
var data = {};
data.user_mail = $scope.user_mail;
data.password = $scope.password;
$http.post('/examplemns.com/customer/api/v1/login/login', data).then(successCallback, errorCallback);

Try changing the following line:
data : $scope.loginData, //forms user object
to:
data : JSON.stringify($scope.loginData), //forms user object

Related

angular js json.stringify to php

Along with the form values, I need additional data to be passed to the PHP script- I have a javascript function "cart.items()" which returns the stringified items that have been selected in the cart. How do I pass this value to the PHP function?
form.html
<div ng-controller="formCtrl">
<input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
<input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
<input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
<button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)" ng-disabled="userForm.$invalid">Submit </button>
</form>
App.js
controller("formCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.url = 'http://localhost/ShoppingCart/ShoppingCart/email.php';
$scope.formsubmit = function (isValid) {
if (isValid) {
$http.post($scope.url, { 'name': $scope.name, "email": $scope.email, "message": $scope.message, "items": $scope.items }).
success(function (data, status) {
// console.log(data);
$scope.items = "this is scope";
$scope.status = status;
$scope.data = data;
$scope.result = data;
//window.location.assign("email.php");
//alert($scope.items);
})
} else {
alert('Form is not valid');
}
index.php
<?php
$post_date = file_get_contents("php://input");
$echo("I want the result of the cart.items() function here");
?>
To make http call use like this. Change according to your ajax call
var requestSignin = {
method: 'POST',
url: your url,
headers: {
"Content-Type" : "text/plain"
},
data: {
field 1: $scope.signinData.email,
field 2: $scope.signinData.password,
.
.
field n .
},
timeout: 30000
};
$http(requestSignin)
.success(function(data) { console.log(data);
}).errror(){
}
Send your fields in data object.
And your php code should be like this.
$post_date = json_decode(file_get_contents("php://input"));
To get the input from request.
while returning from php use json_encode()
Ex:
echo json_encode($cities);

failed bind angularJS variable to nodejs

i have a problem sending my angularJS POST parameters to my nodejs server... i've seen many topics related to this, tried everything here and nothing works (there were more):
How to pass parameter in Angularjs $http.post
Angular: how to pass $scope variables into the Node.js server.
How to pass client-side parameters to the server-side in Angular/Node.js/Express
How to pass data from AngularJS frontend to Nodejs backend?
my relevant code that is envolved in this problem,
handlebars-template:
<div ng-controller='questions'>
<form method="POST" class="form-inline" class="my-search-menu">
<button ng-click="search()" class="btn btn-default glyphicon glyphicon-search" type="submit" style="background-color: #85C1E9;"></button>
<input style="direction: rtl" type="text" name="search_text" ng-model="search_text" class="form-control" placeholder="Search" aria-describedby="sizing-addon3">
</form>
</div>
AngularJS:
var myapp= angular.module('myapp', []);
myapp.controller("questions", function($scope,$http) {
$scope.search = function () {
var formdata = {search_text : $scope.search_text};
$http.post('/search', {params: formdata})
.success(function (data, status, headers, config) {
$scope.questions = data;
})
.error(function(data, status, header, config){
$scope.onerror = "Data: " + status;
});
console.log(formdata);
};
});
NodeJS:
app.post('/search', function (req,res,next){
var search_text = req.query.params.formdata.search_text;
console.log(req);
Question.find({$text: {$search: search_text}}).exec(function (err, questions){
res.json(questions);
});
});
There are few points you are missing. First in the anguar controller
$http.post('/search', {params: formdata})
will send {params:formdata} as request body in the node server.. So in the server end you will receive the data as request.body. correct way to receive the body in this case will be ..
app.post('/search', function (req,res,next){
var search_text = req.body.params.search_text;
//TODO
});
If you want to send the data as parameter then in controller write the function like this...
$http({
method: 'POST',
url: '/search/'+paramData,
}).then(function successCallback(response) {
//TODO
}, function errorCallback(error) {
//TODO
});
And in the server side...
app.post('/search/:searchText', function (req,res,next){
var paramData = req.params.searchText;
//TODO
});

Angular.js Form POST Returns Error 405 Method Not Allowed

I keep getting a 405 error when trying to submit my form. Here's my controller:
'use strict';
angular.
module('myApp').
component('zipPopup', {
templateUrl: 'zip-popup/zip-popup.template.html',
controller: function ZipPopupController($scope, $http) {
$scope.show = true;
$scope.hide = function(){
$scope.show = false;
};
$scope.user = {};
$scope.regex = '\\d{5}';
$scope.submitForm = function(isValid) {
if(isValid) {
$http({
method : 'POST',
url : '/leads',
data : $scope.user,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
$scope.show = false;
})
.error(function(response) {
console.log(response);
});
}
};
}
});
Heres my view:
<div class="zip-popup text-center">
<div class="popup-container">
<form name="zipForm" class="zip-form" ng-submit="submitForm(zipForm.$valid)" novalidate>
<input ng-model="user.zipCode" ng-pattern="regex" name="zipCode" class="form-control text-center" placeholder="Your Zip" required />
<p class="error" ng-show="zipForm.zipCode.$invalid && !zipForm.zipCode.$pristine">A 5 digit zip code is required.</p>
<button type="submit" class="btn btn-block" ng-disabled="zipForm.$invalid">Submit</button>
</form>
</div>
</div>
Is there a different file or something that I need to modify to allow this to happen? What am I missing?
The server is telling you that the particular method (GET, POST, PUT, PATCH, DELETE, etc.) can't be accepted by the server. This is most likely due to the fact that your API route/endpoint doesn't have a POST method configured.
For example, in ExpressJS you'd need to configure a route that accepts POST by doing the following:
app.post('/leads', function (req, res) {
res.send('POST request to the homepage');
});
For more information on the 405 Method Not Allowed error, click here.
I had a similar issue a couple of weeks ago. It turns out that the server was only accepting 'Content-Type' of a particular type in the headers.
However changing the Content-Type to application/json solved the issue:
$http({
method : 'POST',
url : '/leads',
data : $scope.user,
headers : {'Content-Type': 'application/json'}
})
.success(function(response) {
$scope.show = false;
})
.error(function(response) {
console.log(response);
});
P.S. I'm not saying this will necessarily solve your issue, but this is a solution related to this type of problem. Just find out what kind of input your server is expecting.
EDIT
I'm not saying to send 'application/json' as the Content-Type. All I'm saying is that Find what type of content is acceptable and send that type of header.
you try to let the back-end engineer to implement the OPTIONS method.
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Preflight_example

angular js: Error: $ is not defined in http post

I'm trying to post values from a form. Form has two fields- name and email. I have setup the controller as well but when i try to post, error is shown.
<form name="save" ng-submit="sap.saved(save.$valid)" novalidate>
<div class="form-group" >
<input type="text" name="name" id="name" ng-model="sap.name" />
</div>
<div class="form-group" >
<input type="email" name="email" id="email" ng-model="sap.email" />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="save.$invalid || sap.dataLoading">Save</button>
</div>
</form>
My controller is:
(function() {
angular
.module('myApp.saved', [])
.controller('dataController', function($scope, $http) {
var sap = this;
$scope.post = {};
$scope.post.login = [];
$scope.sap = {};
$scope.index = '';
var url = 'save.php';
sap.saved = function(isValid)
{
if (isValid)
{
$http({
method: 'post',
url: url,
data: $.param({'user' : $scope.sap }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response)
{
// success
alert('success');
},
function(response)
{
// failed
alert('failed');
});
}
};
});
})();
When i submit, $ is not defined is shown. I'm pretty much new in angular. Can anyone tell what all mistakes I made?
$ is alias for jQuery and param is a jquery method.
Have you included jQuery?
data: $.param({'user' : $scope.sap }),
should be
data: {
'user': $scope.sap //POST parameters
}
data – {string|Object} – The response body transformed with the transform functions

Accessing Form elements and div from Angular Promise

I am learning angular js. I just want to clear the form fields and show a success div inside a http then().
this.formSubmitted = false;
this.successs = false;
myResumeApp.controller("FormController",['$http', function($http){
this.formSubmit = function(contactForm) {
this.formSubmitted = true;
if(contactForm.$valid)
{
$http({
method: 'post',
url: 'http://jerrythimothy.is-great.net/mailme.php',
data: $.param({
fname : this.fname,
email : this.email,
content : this.content
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
this.successs = true;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});// JavaScript Document
}
};
}]);
<div class="container" ng-controller="FormController as formCtrl">
<h2>Contact me</h2>
<div ng-show="formCtrl.successs" class="alert alert-success fade in" style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">Thank you for contacting me. I will be in touch with you shortly.</div>
<form role="form" name="contactForm" novalidate ng-submit="formCtrl.formSubmit(contactForm)">
Please let me know whether there is anything wrong with my code or any other suggestions. The control is coming inside the then() block. But I need to know how to access the successs element and clear the form fields.
Thank you.
Instead of this, use $scope (and add it to dependencies). Right know your successs property is assigned to different objects (window and callback function).
Controller code:
myResumeApp.controller("FormController",[
'$scope',
'$http',
function($scope, $http){
$scope.successs = false;
$scope.formSubmitted = false;
$scope.msg = {};
$scope.formSubmit = function(contactForm) {
$scope.formSubmitted = true;
if(contactForm.$valid)
{
$http({
method: 'post',
url: 'http://jerrythimothy.is-great.net/mailme.php',
data: $.param({
fname : $scope.msg.fname,
email : $scope.msg.email,
content : $scope.msg.content
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
$scope.successs = true;
$scope.msg = {};
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});// JavaScript Document
}
};
}
]);
HTML code:
<div class="container" ng-controller="FormController as formCtrl">
<h2>Contact me</h2>
<div ng-show="successs"
class="alert alert-success fade in"
style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">
Thank you for contacting me. I will be in touch with you shortly.
</div>
<form role="form" name="contactForm" novalidate ng-submit="formSubmit(contactForm)">
<input type="text" name="name" ng-model="msg.fname" />
<input type="text" name="email" ng-model="msg.email" />
<input type="text" name="content" ng-model="msg.content" />
<input type="submit" value="submit" />
</form>
You should be able to handle that in successCallback.
... .then(function successCallback(response) {
this.successs = true;
contactForm.reset()
}, ...
Also I don't think that this inside successCallback is same as in line where you initialize this.formSubmitted = false;...

Categories

Resources