In angular im using $http.post for sending an id to a php script in order to use this id for a mysql request.
This is my controller:
function ProjectDetailsCtrl($scope, $http, $timeout, getGoodIdProjectDetails) {
$scope.idProjectDetails = getGoodIdProjectDetails.getId(); //Getting id project
$scope.$emit('LOAD')
$scope.url = 'scripts/findProjectDetails.php';
$http.post($scope.url, { "idProject" : $scope.idProjectDetails}).
success(function(data, status) {
$scope.projectDetails = {};
$scope.projectDetails.details = data;
$scope.$emit('UNLOAD')
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
}
idProjectDetails is a number.
Then the Php script :
<?php
$idProject = json_decode($_POST['idProject']);
Php script returns that $idProject is undefined.
Can you help me with this ?
Edit : I tried this way but my app crashed with this :
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http({
method: 'POST',
url: 'scripts/findProjectDetails.php',
data: "idProject" : $scope.idProjectDetails
}).success(function(data, status) {
$scope.projectDetails = {};
$scope.projectDetails.details = data;
console.log(projectDetails.details);
$scope.$emit('UNLOAD')
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
With the first example, in Chrome console, the "request playload" contain this : {idProject:1} idProject:1 so I assume my variable is correctly passed through the php script?
There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.) The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively ... By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
So concretely, your $_POST variable is empty !
To go through this problem there're 2 solutions:
Change the data format in Angular config
Change the way to get the datas with PHP(Deprecated but works)
I haven't invented anything here, just linking...
Hope it'll help.
Related
I am passing an array of values through POST method dynamically.
If i pass more than 50 array values, i am not able to process those data.
I am getting error 505.
I browsed and found that it is an Http error, which refers the post size is not good here.
So i added the properties in my jboss configuarion,
</system-properties>
<property name="org.apache.tomcat.util.http.Parameters.MAX_COUNT" value="-1"/>
</system-properties>
Even after this, i am not able to pass array value more than 50.
Please give some solution for this.
This is my code, in Restfull webservice, where i get data from angular controller.
this.updateConstraint = function($scope, $location, $routeParams) {
var url = hostName + "/dcr/rest/capacityfile/searchcf/blockC/addSubFilesBlocC";
var listSubFiles = $scope.capacityAddSubFile;
var idCapacity = $routeParams.capacityFileId;
var promise = $http({
url : url,
method : "POST",
params :{ subFileCSF : $scope.capacityAddSubFile,
partConstraint : $scope.selectedPartNumberAndConstraint,
partConstraintAdd : $scope.selectedPartNumberAndConstraintAdd,
capacityFileId : $routeParams.capacityFileId},
}).success(function(data, status, headers) {
}).error(function(data, status, headers) {
// alert("Failed to access"+status+" "+headers);
});
return promise;
};
Here the i am getting error, it is showing error 505.
Please reply.
you need to set max-post-size at connector level.
/subsystem=web/connector=http:write-attribute(name=max-post-size, value=80)
I have a strange situation as follows:
The Web-Client application I'm working is based on JQuery and AngularJS,
I have deployed a TOMCAT server (8.5) and a servlet (JAVA-based developed on Eclipse).
The code sending the requests from follows:
var MyApp = angular.module('MyApp');
MyApp.factory('DB_Services', ['$http' , '$q' , function($http , $q) {
var l_Result ;
var DB_Services = function(p_URL_Root , p_Query) {
var l_deferred = $q.defer();
var l_params = JSON.stringify(p_Query) ;
var l_url = "http://localhost:8080/MEKUWQDispatcher/DispatcherClass";
var l_params = 'request=' + encodeURIComponent(JSON.stringify(p_Query)) ;
var req = { url : l_url,
method :"GET",
timeout:10000 ,
headers: {
'Content-Type': 'application/json ; charset=UTF-8'
},
data:l_params
} ;
$http(req ).
success(function(data, status, headers, config) {
l_deferred.resolve(data);
}).
error(function(data, status, headers, config) {
l_deferred.resolve(status);
});
return l_deferred.promise;
return l_deferred.promise;
} ;
return DB_Services;
}]);
Now, the Servlet includes both GET and POST methods. The GET method works in two ways: If the request contains data, it uses the received data to invoke a DB stored procedure. If no data in the request, it invokes a hardcoded select statement (this second behavior is the simple way I found to verify proper connection to the DB, and it would never be activated in real life; moreover, I may eventually delete that part from the servlet's code).
When using a browser (IE, CHROME, all the same result) and enter the address:
http://localhost:8080/MEKUWQDispatcher/DispatcherClass
I get the result of the hardcoded select statement as expected. If, on the other hand, I enter some data to the request, something like:
http://localhost:8080/MEKUWQDispatcher/DispatcherClass?data="request={blabla}"
I get error 400 (bad request).
Now, switching to the javascript, no patter what I do (with or without data) I always get the result of the hardcoded select statement.
I also added the declaration of the servlet within the web.xml file as follows:
<servlet>
<servlet-name>MEKUWQDispatcher</servlet-name>
<servlet-class>MEKUWQDispatcher.DispatcherClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MEKUWQDispatcher</servlet-name>
<url-pattern>/MEKUWQDispatcher</url-pattern>
</servlet-mapping>
Since the original post I made several changes to the service code, being the following a copy of the new code that works like a charm (note also that I switched from GET to POST method):
var MyApp = angular.module('MyApp');
MyApp.factory('DB_Services', ['$http' , '$q' , function($http , $q) {
var DB_Services = function(p_URL_Root , p_Query) {
var l_deferred = $q.defer();
var l_params = JSON.stringify(p_Query) ;
var l_url = "http://localhost:8080/MEKUWQDispatcher/DispatcherClass";
var req = { url : l_url,
method :"POST",
timeout:600000 ,
headers: {
'Content-Type': 'application/json ; charset=UTF-8'
},
params:{request:p_Query}
} ;
$http(req ).
success(function(data, status, headers, config) {
l_deferred.resolve({Server_Response:data , Server_Status: status});
}).
error(function(data, status, headers, config) {
l_deferred.resolve(status);
});
return l_deferred.promise;
return l_deferred.promise;
} ;
return DB_Services;
}]);
I have an issue on my application when I get an API request from members belongs to a particulary group.
GET /api/organizations/1234/members?group=4321
If I start my navigation with this request, I have the right members but if I navigate in other page with other groupe before, the $http response is full of parasite members whereas the response form API is right (check from network tab in Chrome developper tools).
I think about some cache but I can not find it ! For info, I use jsData for mounting my data but it's not seems to be the problem.
Here the code of my function to send Api Request :
var loadGroupMembers = function() {
return $q(function(resolve, reject) {
var callParams = {
organizationId: $stateParams.OrganizationId,
groupId: $stateParams.groupId
};
sendApiCall('groupMembers', 'get', callParams)
.success(function(data) {
resolve(data);
})
.error(function(data) {
});
});
};
var sendApiCall = function(requestId, method, params, data, queryStringParams) {
params = params || {};
data = data || {};
var apiCallConfig = {
params: config.params,
method: config.method,
url: "/api/organizations/1234/members?group=4321",
data: data,
cache : false
};
$rootScope.fn.setHistory($state.current.name, 'apiCall', 'sendManualApiCall:' + requestId);
return $http(apiCallConfig);
};
Please tell me if you have questions or need more details.
Thanks for your help ! :)
Edit : I add the function that call sendApiCall and I made a little apiary to show you how the data from api are : http://private-52326-groupmember.apiary-mock.com/organization/1234/members?group=4321
It was kind of link with Jsdata and an interceptor created by an other developer. For each api request, the interceptor add some data on the response with the same type ... So the issue is closed.
Thanks for your help anyway :)
In PHP side there are some element of array:
$this->data['messages']['ms'][] = 'Line1';
$this->data['messages']['ms'][] = 'Line2';
and method that to return json format:
echo json_encode($this->data['messages']); die();
Angular side:
$scope.response = {};
....
request.success(function (data) {
$scope.response.message = data.messages; // Edit here
});
<div ng-repeat="error in response">{{error}}</div>
When I try to get array items, I get nothing
I have converted my difficult object to array:
$scope.messages = [];
...
// In loop
$scope.messages.push(item);
Output in console:
Array[2]0: "Qeydiyyat mümkün deyil. Bu e-mail ilə istifadəçi artıq saytda qeydiyyatdan keçib"1: "Bu IP ünvanından artıq qeydiyyatdan keçilib"
In HTML template I try to display elements:
<div ng-repat="error in messages">{{error}}</div>
you must check your request. Are you useing $http?
Have you provided http in controller/service?
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
you may also check with console.log(data) if theres any data provided.
Maybe there's different construction than you thought (for example wrapped data)
P.S. it should be messages (with s in the end)
Try this in your angular side.
$scope.response = {};
....
request.success(function (data) {
$scope.message = data.data;
console.log($scope.message);
});
<div ng-repeat="error in message">{{error}}</div>
You call your variable in a wrong way. Try console log the $scope.message if there are data's provided.
Below I've got a function that should make a post to the server.
var updateApplicationMetadata = function(appId, editorVersion, previewPubFile){
var deferred = $q.defer();
var result = $http({
method: 'post',
url: '../resource/applications/'+appId,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
editorVersion: editorVersion,
previewPubFile: previewPubFile
}
});
result.then(function(data){
deferred.result(data);
console.log('from services: ');
console.log(data);
});
return deferred.promise;
};
I call this function like:
$scope.update = function(){
MessageBus.emitMsg('notification','Application updates successful.');
console.log('from update: ');
console.log($scope.application.appId);
console.log($scope.application.editorVersion);
console.log($scope.application.previewPubFile);
DataContext.updateApplicationMetaData($scope.application.appId,$scope.application.editorVersion ,$scope.application.previewPubFile);
};
All of the values sent to the updateApplicationMetaData are valid. I can use the rest client POST man and I can make the post work. When I do it in angular, however, I get a bad request. The URL and header content type are right, but I'm not sure about the data object. It must be malformed. What am I missing here?
You've got an error in your code. You have:
deferred.result(data);
and it should be:
deferred.resolve(data);
for it to work. Also, you need to pass 'application/json' as your accepts type for your data to work.
Assuming you are using the $q service from https://docs.angularjs.org/api/ng/service/$q I don't see a result method. Perhaps change:
deferred.result(data);
To
deferred.resolve(data);
consider using ngResource for rest style json requests
Angular resource docs