I have a problem when I am sending data to Codeigniter via Angular $post. I am using this JS code:
$scope.user.first_name = 'first name';
$scope.user.last_name = 'last name';
$http({
method: 'POST',
url: '/registration',
data: {user: $.param($scope.user)},
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}).then(function successCallback(response) {
console.log(response)
}, function errorCallback(response) {
console.log(response);
});
My PHP is based from another answer from StackOverflow, but still doesn't work:
echo file_get_contents('php://input');
var_dump($this->input->post());
, but in this way I see response empty array, if I say:
var_dump($this->input->post('user'));
I see response NULL, Same is and with:
var_dump(json_encode($this->input->post()));
with or without key "user". Even if I use:
var_dump($_POST);
for the response I get empty array.
How to send and get data via $post Angular service with Codeigniter ?
If you want to send as form encoded data you need to serialize the whole data object with $.param()
Change:
data: {user: $.param($scope.user)},
To
data: $.param(angular.copy({user: $scope.user})),
Or use $httpParamSerializerJQLike
If you use defaults of $http would just be
$http.post( '/registration',$scope.user).then(...
And in php
$data = json_decode(file_get_contents('php://input'));
Related
I am really new to Angular. I am trying to pass a variable to php but the response is " Notice: Trying to get property of non-object" and null for the array.
js file:
var myData = {
fruit1: 'apple',
fruit2: 'banana'
};
$http({
url: "test.php",
method: "POST",
headers : { 'Content-Type': 'application/json' },
data: myData
}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
php file:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$data = $request->myData;
var_dump($data);
The .success and .error methods have been removed from the AngularJS framework. Instead, use the .then and .catch methods:
var myData = {
fruit1: 'apple',
fruit2: 'banana'
};
$http({
url: "test.php",
method: "POST",
̶h̶e̶a̶d̶e̶r̶s̶ ̶:̶ ̶{̶ ̶'̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶'̶:̶ ̶'̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶j̶s̶o̶n̶'̶ ̶}̶,̶
data: myData
}).then(function(response) {
$scope.data = response.data;
return response.data;
}).catch(function(err) {
$scope.status = err.status;
throw err;
});
The $http service automatically JSON encodes data and automatically sets the content type to application/json.
In this case, the code does not use the promise returned by the .then and .catch methods. If the promise is used, it is important to have return and throw statements in the success and rejection handlers.
php file:
$postJSON = file_get_contents("php://input");
$dataArr = json_decode($postJSON, TRUE);
var_dump($dataArr);
The JSON encoded data is found in the body of the POST request. The name of the variable is not sent, only the contents.
The second argument of the json_decode function, specifies that objects be converted to associative arrays.
Keep in mind that these POST requests are subject to same-origin policy. The XHR request must be made from a website page that has the same origin as the page receiving the POST request.
var send=[];
// send[] data contains:
// [{"host":"1","name":"2","password":"3"},
// {"host":"4","name":"5","password":"6"},
// {"host":"7","name":"8","password":"9"},
// {"host":"10","name":"11","password":"12"}]
$http({
method: 'POST',
url: 'file.php',
data: send,
headers: {
'Content-Type': 'Content-type: application/json'
},
}).
success(function(response) {}).
error(function(response) {});
return false;
};
I'm getting errors when I send the data, and I'm not able to parse this data using $_POST. I've tried doing the following:
var obj=(JSON.stringify(send));
data:obj,
and in my PHP file:
$request = file_get_contents('php://input');
$data=json_decode($request);
print_r($data);
If you want to retreive data that was posted, use $_POST['data']:
$request = $_POST['data'];
$data = json_decode($request);
print_r($data);
Could you elaborate what you mean by "I'm getting errors"?
I wrote an angular quiz and I'm trying to send the quiz results to the database for processing. My $http call is as follows:
function saveQuiz() {
quizObj.isSaving = true;
var data = {
id: quiz_id,
action: 'quiz_data',
part: 'save_quiz',
score: quizObj.score,
passed: quizObj.passed,
completed: quizObj.completed,
percentage: quizObj.perc,
time_spent: $filter('formatTimer')(quizObj.counter),
questions: quizObj.quiz.questions
};
console.log(data);
$http({
url: quizapp.ajax_url,
method: "POST",
params: data
})
.then(function(response) {
console.log(response.data);
quizObj.isSaving = false;
},
function(response) { // optional
// failed
console.log(response);
});
}
Notice I am passing an array of json questions as quizObj.quiz.questions.
The problem on the server side is that $_POST['questions'] evaluates to the last item of the quizObj.quiz.questions json object instead of the full list.
Where have I gone wrong?
When using the $http service through Angular, data goes with method: "POST" and params goes with method: "GET"
Change the properties on your config object you are passing to the $http service like so:
$http({
url: quizapp.ajax_url,
method: "POST",
data: data // <-- data here, not params since using POST
}).then(function () { /*...*/ }));
I have to send a json data from Angular to Grails through $http service method. The JSON data has been sent to the server. But in server side it doesn't print the param values. I'm new to Grails.
My Code:
Controller:
$(function(){
gateApp.factory('saveCreateToServer', function($http){
return {
saveDataToServer:function(taskCreateFormData){
console.log(taskCreateFormData);
return $http({
method : 'POST',
url : 'save',
data : taskCreateFormData,
})
}
}
});
gateApp.controller('moveTaskRuleDefCtrl', function($scope, saveCreateToServer){
$scope.saveCreate=function() {
var reqData = angular.toJson($scope.taskCreateForm);
saveCreateToServer.saveDataToServer(reqData).success(function(data) {
});
}
});
})
In Server Side:
def save(params){
println "<<<<<<<<<uu<<<<<<<<<"+params
}
When you post data using $http with data key, the data is not sent as query or form data instead it sent using body parameters. So you can not read it with params, just use request.JSON:
def save() {
Map requestData = request.JSON
println "Data: " + requestData
println "Data: " + requestData.firstName
}
Also, you don't have to convert the object to JSON string, you can just pass the data:
$http({
method: "POST",
url: "/save",
data: {firstName: "John", lastName: "Doe"}
});
Update on passing data as form data
Yes, you can absolutely do it so that you don't have to change the server side code. So basically, Angular by default sends data with Content-Type as application/json so the Grails receives it as request.JSON. So just change it to application/x-www-form-urlencoded:
$http({
method: "POST",
url: "/save",
data: {firstName: "John", lastName: "Doe"},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
Now, the params will be available as params in the Grails controller.
I'm currently using Laravel as my PHP framework, where I've setup an Api Class which goes off and calls an external API.
However I'm looking to use this functionality over AJAX, with AngularJS, where I'm currently struggling to pass data from Javascript. Here's how it works:
The PHP API GET Call:
Api::get('users/all', ['order' => 'desc']);
This would create a GET request, to the api with the parameters order=desc. However so I don't have to create a route for each api call, I want to do this dynamically:
Angular service:
app.factory('Api', function($http) {
return {
query : function( method, path, data ) {
return $http({
method: 'POST',
url: 'api',
headers: { 'Content-Type' : 'application/json' },
data: { 'method': method, 'path': path, 'data': data },
});
},
}
});
Then my PHP controller:
$method = Input::get('method');
$path = Input::get('path');
return Api::$method($path);
So this works, however I'm struggling to pass the 3rd array parameter from JS to PHP.
var json = '{"order": "desc"}';
Api.query('get', 'users/list', json)
.success(function(response) {
$scope.test = response;
});
In my PHP, I've tried to json_decode it with no success (no errors actually):
$method = Input::get('method');
$path = Input::get('path');
$data = json_decode(Input::get('data'), true);
return Api::$method($path, $data);
Anyone got any clues what the best way around this is?