I am Passing my user information http angularjs. backend code is PHP
As I am the beginner I am searching lot for this Issue. and tried a lot methods since 2 days but I couldn't find the reason, and how to fix it?. it may be simple but I couldn't find.
1.I am posting my http post request in angularJS I have been debugged the value which I will send is
Debugging value are as follow:
serializedParams:"send_id=78&send_name=Douby&send_phone=4528&send_status=Due"
url: "insert.php?send_id=78&send_name=Douby&send_phone=4528&send_status=Due"
result: undefined
I think the url is correct. but the result is undefined
var app = angular.module("myapp", []);
app.controller("booking", function($scope, $http) {
$scope.paidops = ["Paid", "Due"];
$scope.value = "ADD";
$scope.insertvalues = function() {
alert($scope.id + ' , ' +
$scope.name + ' ,' + $scope.phone +
' , ' + $scope.status);
alert($scope.name);
var Indata = {
'send_id': $scope.id,
'send_name': $scope.name,
'send_phone': $scope.phone,
'send_status': $scope.status
};
$http({
method: 'POST',
url: 'insert.php',
params: Indata,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
alert(JSON.stringify(response));
}, function(response) {
alert(response);
});
}
});
In PHP I am getting data like this way:
$connect = mysqli_connect("localhost:3307", "root", "", "ticket_booking");
if($connect === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$data = json_decode(file_get_contents("php://input"),true);
if(count(array($data)) > 0)
{
$id_received = mysqli_real_escape_string($connect, $data->send_id);
$name_received = mysqli_real_escape_string($connect, $data->send_name);
$phone_received = mysqli_real_escape_string($connect, $data->send_phone);
$status_received = mysqli_real_escape_string($connect, $data->send_status);
$btnname_received = mysqli_real_escape_string($connect, $data->send_btnName);
if($btnname_received == 'ADD'){
$query = "INSERT INTO society_tour(id,name, phone, status) VALUES ('$id_received','$name_received', '$phone_received','$status_received')";
if(mysqli_query($connect, $query))
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
}
?>
Not entirely sure about the PHP part, but as you have json_decode in PHP, its safe to assume that PHP expects a JSON content-type
If so, here is how to post data to a url
var postUrl = 'insert.php'; // please check whether the url is correct
var dto = {
'send_id': $scope.id,
'send_name': $scope.name,
'send_phone': $scope.phone,
'send_status': $scope.status
};
$http({
url: postUrl,
method: 'POST',
data: dto,
headers: {
"Content-Type": "application/json"
}
})
//...
Related
why is this time out not working? I have injected $timeout in controller. Even moving timeout into http response is the same. Using angularjs 1.6.6 with Laravel 5.2. $scope.showInfo is true, but not false after 3000 ms.
$scope.submitAttendance = function(attData) {
$http({
method: 'POST',
url: '/api/save/attendance',
headers: { 'Content-Type' : 'application/json' },
data: attData
}).then(function successCallback(response) {
var response = response.data;
if (response == 1) {
$scope.msg = 'Attendance details saved to system';
$scope.attData = {};
$scope.attData.timeIn = new Date (new Date().toDateString() + ' ' + '08:00');
$scope.attData.timeOut = new Date (new Date().toDateString() + ' ' + '16:00');
} else {
$scope.msg = 'Failed to save Attendance info';
}
}, function errorCallback(response) {
$scope.msg = 'There is a problem saving data at this time. Please contact Administrator';
});
$scope.showInfo = true;
$timeout(function(){ $scope.showinfo = false; }, 3000);
}
I am trying to use Angular to authenticate against an authorization endpoint that I know works using Postman.
<script type="text/javascript">
var tokenGeneratorApp = angular.module('myApp', []);
myApp.controller('AuthenticationController', function ($scope, $http) {
var ac = this;
ac.authorizationToken = null;
ac.getAuthorizationToken = function () {
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
},
headers: {
'Content-Type': 'application/json'
}
}).then(_authenticationSuccess, _authenticationError);
};
// Private methods to handle promise results
function _authenticationSuccess(response) {
ac.authorizationToken = response.data;
ac.resultsDisplay = ac.authorizationToken;
};
function _authenticationError(response) {
ac.resultsDisplay = 'An error occured: ' + response.data;
};
});
</script>
When I call getAuthorizationToken()I get an Http 400 back. When I look into the response.data object there is an error saying error:"unsupported_grant_type". This is confusing to me because in the Postman client I specify that the grant_type as password and all works as expected.
I must be doing something wrong in the Angular code.
Had a very similar problem recently. Try removing the 'headers' and insert 'dataType' instead, as follows:
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
dataType: "json",
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
}
EDIT
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
"username=" + theUserName + "&password=" +
thePassword + "&grant_type=thePassword"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
//resolving => error:"unsupported_grant_type"
vm.BtnLogin = function () {
$scope.txtUsernamee;
$scope.txtPasswordd;
var client_credentials = $scope.txtUsernamee + $scope.txtPasswordd;
var auth = 'username=' + $scope.txtUsernamee + '&' + 'password=' + $scope.txtPasswordd + '&grant_type=password';
$http({
method: "POST",
url: '/token',
contentType: 'application/json',
data: auth
}).then(function success(response) {
//$('#successModal').modal('show');
console.log("ok")
},
function error(e) {
console.log(e)
}
);
};
i am returning a string on updation of a record and want to show the same string on UI(updated successfully)
Here is my code :
#RequestMapping(method = RequestMethod.PUT, value = "/update")
public #ResponseBody String update(#RequestParam("id") int id, #RequestParam("name") String name) {
employeeService.update(id, name);
return "updated successfully";
front end code :
$scope.update = function(Employee) {
$http({
method : 'PUT',
url : '/Employee/update',
params : {
id : Employee.id,
name : Employee.name
}
}).success(function(data, status, headers, config) {
$scope.updatedText = data;
$scope.updatedFlag = true;
}).error(function(data, status, headers, config) {
console.log("data.token " + data.token);
});
};
Here are two interesting screen shots
here status is undefined
again
here status is 200
please let me know what is the reason behind that and yes i can see that there is a change in the hibernate table
Please help
Well i'll leave you an example how i handle calls to the API with $http and promises $q
i use it inside a service, that can be injected on my controllers.
this.update = function (Employee) {
var datosRecu = null;
var deferred = $q.defer();
var token = $cookies.getObject('token');
$http({
url: '/Employee/update',
method: 'PUT',
params: {
id: Employee.id,
name: Employee.name
},
headers: {
'Authorization': 'Bearer ' + token,
'Content-type': 'application/json'
}
}).then(function successCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
}, function errorCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
});
return deferred.promise;
};
now when i inject it on my controller i can read the promise deferred.promise with all the data of response.
i hope it help you.
I'm trying to create a chat app where you can log into the incontact chat api (discard the weatherApp naming.. ).
This is the API documentation for the incontact chat api:
function startAgentSession() {
var startSessionPayload = {
'stationId': 'string',
'stationPhoneNumber': 'string',
'inactivityTimeout': 'integer - 30-300, or 0 for default',
'inactivityForceLogout': 'boolean',
'asAgentId': 'integer'
}
$.ajax({
//The baseURI variable is created by the result.base_server_base_uri
//which is returned when getting a token and should be used to create the URL base
'url': baseURI + 'services/{version}/agent-sessions',
'type': 'POST',
'headers': {
//Use access_token previously retrieved from inContact token service
'Authorization': 'bearer ' + accessToken,
'content-Type': 'application/json'
},
'data': JSON.stringify(startSessionPayload),
'success': function (result) {
//Process success actions
return result;
},
'error': function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
return false;
}
});
``}
This is my attempt to convert in angular js, but for some reason I keep getting a 404, however, I'm at a loss for what I've done wrong..
weatherApp.controller('launchedController', ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.clientResult = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '55555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}).success(function(data) {
$scope.data = data;
consoloe.log('data', $scope.data)
}).error(function(status) {
$scope.status = status;
});
}]);
400 error is bad request. My guess is
replace
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}
with
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: $scope.startSessionPayload
}
So looks my request:
angular.module('todoApp').factory('UsersService', ['$resource', 'paramsService', '$q', function($resource, paramsService, $q){
var server = paramsService.serverUrl;
return {
'auth': function(username, password){
var $response = {};
$resource(server + '/api/account/auth', {}, {call: {method: 'POST', headers: {'Content-Type': 'application/json'}}}).call(
{'username': username, 'password': password},
function(data){
console.log(data);
$response = data;
}
);
console.log($response);
return $response;
},
}
}]);
At success function i hava response in data, but variable $response is empty. I know but why it happens, but can't find way to wait response to return it. How can i get response from $resource?
As charliefl commented you need to use the promise object returned from the $resource request to await the completion of the function ($resource is asynchronous).
My PHP code for handling the POST request returned the number of bytes written to the file. I parsed that back from the response using the code below. Since the 'resource' object was not a true array (like 'arguments') I had to loop through possible indices until one returned 'undefined'.
So the bottom line is whatever is in your response body will be returned to you as an array of bytes on the resource object.
$resource(...POST REQUEST...)
.$promise.then(function (resource) {
var bytesSaved = '';
var i = 0;
while (resource[i] !== undefined) {
bytesSaved += resource[i];
i++;
}
$scope.lessonMsg = 'File saved, ' + bytesSaved + ' bytes'
}
function(error) {
$scope.msg = 'An error occurred trying to save the file. ' + error;
}
);
Here is the PHP code generating the POST response:
case "POST":
$params = explode("file/", $_SERVER['REQUEST_URI']);
$filename = '../common/resources/fileContents' . $params[1] . '.json';
$data = file_get_contents("php://input");
$data = json_decode(file_get_contents("php://input"),false);
$fileJson = file_put_contents($filename, json_encode($data));
echo $fileJson;
break;
The file_put_contents() call returns the number of bytes written or false if there was an error.
Hello #falloff please try with below code snippet, I think this will work for you. Also, let me know whether It works or not.
angular.module('todoApp').factory('UsersService', ['$resource', 'paramsService', '$q', function($resource, paramsService, $q){
var server = paramsService.serverUrl;
return {
'auth': function(username, password){
let resource = $resource(server + '/api/account/auth', {}, {
save: {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
},
});
resource.save(
{'username': username, 'password': password}, (response) => {
if (response.length !== 0 && response.length === 0) {
// You will get respose here in 'response'
}
else {
// If response is null
}
deferred.resolve('request successful');
},
(err) => {
// Error
deferred.reject(err);
});
},
}
}]);