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

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..

Related

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

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.

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

Angular post request to php failed

I have a simple form with two fields.
<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>
I'm trying to post these values to a php page using POST request.
$http({
method: 'post',
url: 'save.php',
data: $scope.vm,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config)
{
if(data.success)
{
alert('valid');
}
else
{
alert('invalid 1');
}
}).
error(function(data, status, headers, config)
{
alert('invalid 2');
});
And in save.php file, I'm fetching the values like this:
$name=$_POST['name'];
$email=$_POST['email'];
But response I get is undefned variable name. That's a PHP notice. But when I try to POST these values from POSTman client, it works.
Is there anything wrong with the method I choose to POST data?
P.S: i didn't post entire controller. Just http request part is included here.
I faced same situation where $_POST() did't worked out!
trying to fetch raw data with:
json_decode(file_get_contents('php://input'))
might be helpful.
Update:
This Answer explains why $_POST variable is not populated in php
when data is posted with angular!

AngularJS and PHP - Notice: Undefined property: stdClass

I have a simple PATCH http request from AngularJS to PHP and I'm getting the error Notice: Undefined property: stdClass::$todoName in my console. Here are the codes:
html
<div ng-controller="UpdateTodoController">
<div class="input-field col s12" ng-repeat="t in todo">
<input id="{{ t.id }}" type="text" class="validate" ng-model="todoName">
<label class="active" for="{{ t.id }}">{{ t.name }}</label>
<button class="btn waves-effect waves-light" ng-click="updateTodo(t.id)">Update
</button>
</div>
</div>
Controller
function UpdateTodoController($http, $scope, $routeParams, $location) {
$scope.updateTodo = function(todoId) {
var req = {
method: 'PATCH',
url: 'app/endpoints/update-todo.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
todoName: $scope.todoName,
todoId: todoId
}
}
$http(req)
.then(function successCallback(response) {
$location.url('/');
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
}
}
update-todo.php
$data = json_decode(file_get_contents('php://input'));
$todoId = $data->todoId;
$todoName = $data->todoName;
$statement = $db->prepare("UPDATE todo_list SET name=? WHERE id=?");
$statement->execute(array($todoName, $todoId));
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
It updates the specific field with the id but gives a NULL value. Am I missing something here? Thank you.
You are sending data form-urlencoded but trying to use json_decode on it.
Remove the Content-Type header from angular request.
$http default is to send application/json.
A simple test would be to return a dump of $data and inspect in browser dev tools

Categories