AngularJS and PHP - Notice: Undefined property: stdClass - javascript

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

Related

Axios does not pass (data) to the request

Sorry for my English!
I work with Axios not so long ago, I am constantly tormented. Actually, I need to transfer the “data” from Vue through Axios for myself to the PHP controller, after the Axios method is triggered, I do dd ($ request) and see the void, tell me what could be the problem, thanks!
P.S. I am still confused that the 'data' in the console is displayed in 'config' and in the field 'data' above some kind of giant script is above the config. So it should be? or is there a problem? (see screenshots of the console below).
<div id="blank">
<form>
<div class="form-grup">
<label></label>
<input type="text" class="myform" name="kladr" v-model="kladr">
</div>
<div class="form-grup">
<label></label>
<input type="text" class="myform" name="ownerKladr" v-model="ownerKladr">
</div>
<div class="form-grup">
<label></label>
<input type="text" class="myform" name="insurancePeriod" v-model="insurancePeriod">
</div>
<button #click.prevent="storeBlank">Accept</button>
</form>
</div>
var blankjs = new Vue({
el: '#blank',
data() {
return {
kladr: '',
ownerKladr: '',
insurancePeriod: ''
}
},
methods: {
storeBlank() {
let url = '/blank/' + encodeURIComponent(this.user) + '/save';
let data = {
kladr: this.kladr,
ownerKladr: this.ownerKladr,
insurancePeriod: this.insurancePeriod
}
axios.post(url, data)
.then(function (response) {
console.log(response)
})
}
}
})
// PHP
/**
* #Route("/blank/{user}/save", name="save_blank")
*/
public function storeBlank(Request $request, User $user): Response
{
dd($request); //or dd(json_encode($request));
}
This is what I get in console.log:
data: "<script> Sfdump = window.Sfdump || (function (doc)…re><script>Sfdump("sf-dump-1008019515")</script>↵", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config:
adapter: ƒ (e)
data: "{"data":{"kladr":"", "ownerKladr":"", "insurancePeriod":""}}"
headers:
Accept: "application/json, text/plain, */*"
Content-Type: "application/json;charset=utf
Your data is inside of data object. Here is example:
axios.post(url, data)
.then(function (response) {
console.log(response.data);
});
Also your request can be failed. You can handle error witch catch method.
axios.post(url, data)
.catch(function(error){
//if your request fail this block will be executed. otherwise 'then' statement will work
})
.then(function (response) {
console.log(response.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
}
});
}

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.

How to bind value with $scope to view with ng-model from controller that define in state ui-router?

I used mechanism for transferring state ui-router. With state "inputcontract" that I have defined, when processed (http://cem.survey.local/#/inputcontract/SGD621262), it will pass parameter "sohd" to function "$scope.getSurveyContent($scope,sohd)" in controller "accountController" , this function will send the request to the server to retrieve data returns in json structures. The problem is that I cannot bind value to view by using $scope with json return "$scope.account =response.data_cusinfo[0]", if bind successfully it will appear dynamic on view HTML. How can i do that? Thank you very much.
Here is app.js
var app = angular.module('outbound', ['ngMaterial', 'ui.router'])
.constant('API_URL', 'http://cem.survey.local/');
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('inputcontract', {
url: "/inputcontract/:sohd",
controller: 'accountController'
})
})
Here is accountController.js
app.controller('accountController', function ($scope, $http,$templateRequest, $sce, $compile, $mdDialog, $mdSidenav, $mdMedia, API_URL, $stateParams) {
if (typeof $stateParams.sohd === 'undefined') {
return;
}
$scope.account = {};
var sohd=$stateParams.sohd;
$scope.getSurveyContent= function($scope,sohd)
{ var url = API_URL + "account/search";
$http({
method: 'POST',
url: url,
data: {sohd: sohd},
headers: {'Content-Type': 'application/json'}
}).success(function (response) {
$scope.account =response.data_cusinfo[0];
}).error(function (response) {
});
}
//Send Request to server with sohd
$scope.getSurveyContent($scope,sohd);
Here is the view
<html lang="en-US" ng-app="outbound">
...
<div ng-controller="accountController">
...
<td style="width: 150px">Khách hàng
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.CustomerName" >
</div></td>
<td>CMND
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.Passport" >
</div>
</td>
<td>Ngày tháng năm sinh
<div class="form-group">
<input class="form-control" id="inputdefault" type="text"
ng-model="account.Birthday">
</div></td>
...
</div>
...
</html>
Assuming the $http post is successful, you don't need to pass $scope on your getSurveyContent function. Also, success and error are deprecated - you should use then. Try this:
$scope.getSurveyContent = function(sohd) {
var url = API_URL + "account/search";
$http({
method: 'POST',
url: url,
data: {sohd: sohd},
headers: {'Content-Type': 'application/json'}
}).then(
function successCallback (response) {
$scope.account = response.data.data_cusinfo[0];
},
function errorCallback (response) {
}
);
}
//Send Request to server with sohd
$scope.getSurveyContent(sohd);

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