AngularJS $http.post and PHP - javascript

I'm using AngularJS to $http.post an object, but I also want to include some kind of data in the URL (or some other way) to specify what this object contains and where to parse it in the PHP file. Any idea how I can send a variable similar to GET into the AngularJS post so in PHP I can route the object to the correct if statement for parsing?
Here is my AngularJS code:
$scope.saveSchool=function(){
var schoolData = angular.copy($scope.schoolsModal);
$http.post('data/data.php?schoolModal=save', schoolData).error(function(){
console.log('Did not post data to data.php');
});
};
And here is my PHP code in data.php file in hopes to receive and route the object to the correct if statement for parsing and eventually saving the data.
if (isset($_GET["schoolModal"])) {
if ($_GET["schoolModal"] == "save") {
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo "Acknowledged";
echo $postdata;
}
}
This doesn't work, as it doesn't throw any errors or return anything (PHP). This does work, but I'm unable to route the object in the php file (i would have to create a separate php file just for this angularjs json object).
$scope.saveSchool=function(){
console.log('saveSchool function initiated');
var schoolData = angular.copy($scope.schoolsModal);
$http.post('data/data.php', schoolData).error(function(){
console.log('Did not post data to data.php');
});
};
PHP Script that would need to be in it's own file, as I want to eventually have multiple post functions and parse the data as it's received:
if($_SERVER['REQUEST_METHOD']=='POST'){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo $postdata;
}
That PHP code works just fine, but i'm unable to route the data to where it needs to go. I don't want to send ALL posts to that if statement. Any ideas, I'm new to AngularJS and PHP and doing my best to pick this up.

Consider this example from a project I did. It only has 1 param 'status', but obviously you can add all of your params to an object like that
postFavorite: function(id, type, record, resource) {
var xsrf = $.param({status: record.prop});
$http({
method: 'POST',
url: this.api_base + '/favorites/'+type+'/'+id,
data: xsrf,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
withCredentials: true
}).success(function(data, status, headers, config){
if(data.success){
console.log("Success:", data, status, headers, config);
}
});
},

Related

Angular + PHP: Simplest way to POST an object?

I'm studying php and angular. Currently exploring the possibilities to send data to server side using $http service. This is what I came up with and it seem to work, but it doesn't look elegant.
Angular code:
$http({
method: 'POST',
url: 'server.php',
data: "newUser=" + JSON.stringify(user),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
})
.success(function (respose) {
var x = JSON.parse(respose);
console.log(JSON.parse(x));
}).error(function (err) {
console.log(err);
console.log("some kind of error");
});
This is my php code to receive the data and return it:
if (isset($_POST["newUser"])) {
$newUser = $_POST["newUser"];
echo json_encode($newUser);
}
Why do I have to specify the name of the json I'm passing? I mean the newUser prefix under the data of the request.
Secondly, why do I have to json.parse twice the response in order to convert it back to a JS Object?
Why to I have to specify the headers in order to pass a simple JSON string?
Q1. Why do I have to specify the name of the json I'm passing? I mean the newUser prefix under the data of the request.
Q3. Why to I have to specify the headers in order to pass a simple JSON string?
In PHP, you have global arrays like $_POST & $_GET to receive the data extracted from the request that are on the form of key=value.
And $_POST is filled when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type.
So in order to use these global arrays, you have to full-fill these two conditions
Okay the alternative way is to use php://input stream to directly read the raw input, so you can send the json string directly.
file_get_contents(“php://input”);

variable posted from angular to php using $http.post() is not working

I posted a variable from a angularjs controller to a php file in the same folder using $http.post() method. But in the php page I am able to retrieve the variable. The variable is being undefined.
Here is the angular code
$scope.checkout = function(){
$http({
url:"checkout.php",
method : 'POST',
data :{
'total':$scope.total
},
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data, status, headers, config) {
window.location.href = 'checkout.php'
}).error(function(data, status, headers, config) {
console.log("not done");
});
}
and here is the php code
<?php
$_SESSION['bill_amount'] = $_POST['total'];
echo $_SESSION['bill_amount'];
?>
But I am getting the error that total is undefined.
You are sending data but Angular by default send it as in JSON format and you need to decode the JSON so in your php file decode the JSON by using json_decode function.The full code is given below:
<?php
$data = json_decode(file_get_contents("php://input"));
$total = $data->total; // $_POST['total'];
$_SESSION['bill_amount'] = $total;
?>
I found the answer. I created a middle page called middleware.php where I am storing the post data to session variables and on success I am redirecting to checkout.php and using the post values through session variables.

Angular - send HTTP post data to server [HOW TO]

I'm trying to send data from my login FORM to backend writen in PHP using POST method.
my Angular code looks like:
$scope.getToken = function(){
// console.log $scope.login to make sure I'm not sending empty data
console.log($scope.login);
$http({
method: 'POST',
url: '../../api/v1/Oauth.php',
data: { 'login' : $scope.login, 'password' : $scope.password }
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
});
};
and after that I try to catch it on my PHP:
if((isset($_POST['login']) AND isset($_POST['password'])))
{
$username = $_POST['login'];
$password = $_POST['password'];
echo $username;
}
else
var_dump($_POST);
This statement always go to else and return empty array.
Can someone advise me what I'm doing wrong or how can I debug this?
Because it looks that I send data fron angular correctly but it didn't come to server.
Thanks
Kind Regards
Andurit
Use this:
json_decode(file_get_contents('php://input'));
Check your network tab in your developer bar. You can see that you send payload data in the http body. That's why the $_POST array is empty.
Some older server side web libraries like Coldfusion/.NET/PHP have issues grabbing a POST BODY by default (which is how $http sends the data).
You can reference How to get body of a POST in php? to learn how to write your PHP in a way that it will accept the current and correct standard of sending data via a post.
To access the entity body of a POST or PUT request (or any other HTTP
method):
$entityBody = file_get_contents('php://input');
Also, the STDIN constant is an already-open stream to php://input, so
you can alternatively do:
$entityBody = stream_get_contents(STDIN);
try:
data: { login : $scope.login, password : $scope.password }
$http.post('url', {login: 'Alex', password: 'qwerty'}).then(function(){},function(){});

Why is my Angular POST request to a PHP page not setting up the POST array?

I have a angular post that sends to my php file, but in the PHP file, I cannot access anything from the post variable. It returns my SUCCESS string, but nothing after that, so my return on the post is "SUCCESS - - - - - " where the data should be between the dashes.
JSON/JS object:
DESCRIPTION: "123321"
LOCATION: "ab_calgary_eighth_ave_pl"
NAME: "123321"
QUANTITY: 123321
TYPE: "cycle"
Angular POST Code:
$scope.insertNewInventoryItem = function()
{
if(typeof ($scope.newItem.LOCATION) == 'undefined')
alert("LocationCannot Be Empty. Please Select An Option From The Drop Down.");
else if(typeof ($scope.newItem.TYPE) == 'undefined')
alert("Type Cannot Be Empty. Please Select An Option From The Drop Down.");
else
{
$http.post("dataaccess/addnewinventory.php", $scope.newItem).then(onAddNewComplete, onAddNewError);
}
}
PHP Page attempting to find the posted values:
<?php
$con = mysqli_connect("localhost", "dbadminuser", "password", "database_demo_inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "FAIL - Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "SUCCESS - " . $HTTP_POST_VARS['newItem.NAME'] . " - " . $HTTP_POST_VARS['TYPE'] . " - " . $HTTP_POST_VARS["QUANTITY"] . " - " . $HTTP_POST_VARS . " - " . $_POST[0];
}
mysqli_close($con);
?>
Picture of the Request from GOOGLE developer tools:
Picture of return data from the request (see PHP code for where SUCCESS is coming from):
Why can I not access the post variables? Am I missing something here?
By default, Angular transmits data using the Content-Type: "application/json" and PHP can't parse the JSON data into the $_POST natively. You could follow these two steps to resolve this issue:
Step 1: Change the default value of header Content-Type:
angular.module("myApp",[], function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
})
Step 2: Convert the JSON data into key=value pair serialized data. (I'm using jQuery $.param function to convert the data)
$http({
method:"POST",
url: "post.php",
data: $.param($scope.newItem)
}).success(function(data, status, headers, config){
console.log(data);
}).error(function(data, status, headers, config){
console.log(status);
});
Note: $HTTP_POST_VARS is not a super global variable and it has been completely deprecated in PHP 5. I think you could use $_POST.
while chickenrice's answer is true and solves the issue, I'd prefer to use the JSON data as the payload at least for few reasons.
suits if your objects are complicated, contains nested structures.
It allows you to send any kind of object e.g. [[1,2],[3,4]] -
Array(array,array..) This is just impossible to send in uri-encoded
string.
It's not comfortable if you send simple "name=egor&type=lulzsec"
since it will look "verbose".
You CAN omit CSRF tokens with this!
To get this in PHP make use of file_get_contents("php://input"); to get the request body directly.
You would need to have a small wrapper around this. Moreover you might need to whitelist the content type headers to mitigate the CSRF.
EDIT
if (0 === strpos($_SERVER['CONTENT_TYPE'], 'application/json')) {
$input_json = file_get_contents('php://input');
$input= json_decode( $input_json, TRUE ); //convert JSON into array
}
My backend is Apache22/PHP5.4. I've been banging my head against the wall on this issue for days. Just now, I finally cracked it.
Setting content-type to application/x-www-form-urlencoded didn't get the data into input:// or $_POST. Then I came across this thread: https://groups.google.com/forum/#!topic/angular/MBf8qvBpuVE
Not setting Content-Type will make the underlying XHR browser implementation add a correct header
The keys is to set content-type: false. This is my working code, and I don't even have to get the data from input:// it goes directly to $_POST.
var serialized = $httpParamSerializer($scope.formData);
return $http({
method : 'POST',
url : 'your-url-here',
data : serialized,
headers : { 'Content-Type': false }
}).then(
function(response) {
return response;
},
//Network or server error
function(data, status, headers,config,statusText) {
console.log('AJAX failure: status='+status+', statusText='+statusText);
}
);
I am very new to AngularJS, and so I have no idea why setting the header didn't work for me.
For decoding the PHP, I used the following code, which gave me direct access into the POST data, which in my case was JSON. Apparently JSON is a unsupported data structure, so PHP failed to parse it automatically into the POST array:
$jsonText = file_get_contents('php://input');
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode('[' . $decodedText . ']', true);
Explanation:
Line 1 gets the raw data that was sent over from the request (in this case it was from the Angular Controller posted in the OP.
Line 2 decodes the JSON array grabbed in step one, correctly forming it to parse later. Note that in this case, steps one and two both return the exact same looking object.
Line 3 takes the formatted JSON data and decodes it into a PHP array. Now you can use the following to access parts of the array:
$myvar = $myArray[0]["SOME_VARIABLE"];
Thanks for the answers guys!

Get Ajax POST data on php via Javascript call

First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}

Categories

Resources