Angular $http and PHP - php

I cannot make the following code to work!
<input type="text" ng-model="name" >
<button ng-click="send(name);">SEND</button>
angular.module('myapp', []).
controller('MyController', ['$scope','$http', function ($scope,$http) {
$scope.name='Jim';
$scope.send=function() {
return $http({
method: 'POST',
data:{server:'Hi'},
url: 'test.php',
dataType: 'json'
}).then(function(data){console.log(data)},function(data){console.log('failure')});
};
}]);
and my very simple test.php:
<?php
$request=$_POST['server'];
$request.='Jim';
echo json_encode($request);
?>
By pressing button SEND, I am getting ($http returns successfully): Object {data: ""Jim"", status: 200, config: Object, statusText: "OK"}. Why data equals that object and why 'Hi' is not passed to PHP?
Please, someone to help. I am going to be crazy!

Probably because in your PHP script you are reading in wrong way the body of the request, try that:
<?php
header("Content-Type: application/json");
$entityBody = file_get_contents('php://input');
$request = json_decode($entityBody);
$request->server .= ' Jim';
echo json_encode($request);
?>

I just ran into this problem a few days ago. Angular $http doesn't serialize data for POST like php is expecting, and I don't think Content-Type is set correctly either. If you want php to get the request variable $POST as it's expecting and not have to read from 'php://input', you need to serialize your post data and make sure Content-Type is correct. This is what worked for me.
$http({
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
data: formatPostData( {server:'Hi'} ),
url: 'test.php',
dataType: 'json'
})
And the funtion used to serialize post data is like this.
function formatPostData( args ) {
var postString = '';
angular.forEach( args, function(v, k){
postString += k + '='+encodeURIComponent(v)+'&';
})
return postString.slice(0, -1);
}

Related

Pass angularjs value to PHP variable

I am starting with angularjs with ngStorage. I can save and display data successfully.
I display value as before
{{myobj.session}}
I would like to pass whatever stored value into php variable. Shown below is my imaginary logic and I know thats not gonna work. My question is how to assign such value into PHP variable in a correct manner?
<?php
$name = {{myobj.session}}
?>
You can use this angular variable: students.tiffen_type
PHP variable : $value
<?php
$value = "{{ students.tiffen_type }}";
?>
You can do a ajax request like this:
$http({
url: "urltopost.php",
method: "POST",
data: {
data: variable
}
}).success(function(response) {
console.log(response);
});
And on the backend you can get the variable like this
<?php
$request = json_decode( file_get_contents('php://input') );
$variable = $request->data
From there you can do everything you want with that variable, still I'm not sure what are you trying to achieve.
You can't assign directly angularjs value to php variable, use the following method it will help you
$http({
method: "POST",
url: "test.php",
data: {
data: postvariable
}
}).success(function(response) {
console.log(response); //get the echo value from php page
}).error(function(response) {
console.log(response);
});
test.php
<?php
$data = json_decode(file_get_contents("php://input"));
echo $data->data;
?>
send.js
$http({
method: "post",
url: "ajax/request.php",
data: {
angular_var: $scope.angular_var // $scope.angular_var is angular variable e.g. ng-model="angular_var"
}, headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log(data)
});
ajax/request.php
$request_arr = json_decode( file_get_contents('php://input') );
$angular_var = $request_arr->angular_var;

JSON Padding With PHP

Please can anyone assist I'm trying to get my JSON data displayed on my html5 localhost page,
I'm still new to JSON
I get the following returned but no data is loading on the page.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
Please if anyone can assist.
Below is my php script
`mysql_select_db($database_xxx, $xxx);
$rsfet = "SELECT * FROM cs_tracking ";
$fet = mysql_query($rsfet, $xxx) or die(mysql_error());
$json = array();
while($r=mysql_fetch_array($fet)){
$json[] = $r;
}
header('Access-Control-Allow-Origin: *');
echo $callback ='('.json_encode($json).')';`
and my javascript to display the table data
`
$(document).ready(function(){
$.ajax({
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: true,
success: function(data){
$.each(data,function(i,photo){
var tblRow =""
+""+data.CS_Track_Child+""
+""+data.CS_Track_Date+""
+""+data.Tracking_Status+""
+""+data.CS_Tracking_ID+""
+"" ;
$(tblRow).appendTo("#userdata tbody");
});
},
});
});`
The $callback variable is not magically declared in your script (at least, it shouldn't be); you can access the value via $_GET['callback'] but make sure to sanitize its value:
if (isset($_GET['callback']) && preg_match('/[A-Z]\w*/i', $_GET['callback']) {
header('Content-Type: application/javascript');
header('Access-Control-Allow-Origin: *');
printf('%s(%s);', $_GET['callback'], json_encode($json));
}
You have two GET parameter of callback one is valid but empty and second is invalid.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
So remove your parameter and try with this:
url: 'http://xxxxxxxxxxx.com/getCheck.php',

How to post a data in Angular?

I try to make a post query to save my array in database. server side is PHP. My angular part:
$http({
method: 'POST',
url: "addOrder.php",
data: myJsonedArray,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
Angular make a post query to addData.php, but in php file my command
print_r($_POST); or print_r($_REQUEST);
give me empty Array();
How to fix it? Thanks
UPDATE:
if I try this example in jquery - I have he same result - empty array, but if I try with "test_var" - example works well:
$.post("addOrder.php", { "test_var": da }, function (data) {
console.log(data);
});
How to make the same result? I've tried
$http({
method: 'POST',
url: "addOrder.php",
data: { "test_var": da },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
but no result (
Perhaps this helps: http://www.cleverweb.nl/javascript/a-simple-search-with-angularjs-and-php/
$data = file_get_contents("php://input");
$objData = json_decode($data);
Also, I find $resource much easier to use...

AJAX Returns Null in Firefox/IE but Object in Chrome

I've been bashing my head against the computer trying to figure this out. My AJAX call/request returns the correct object in Chrome but in Firefox/IE8 it returns null. I've tried stripping down my function to a simple array with one value/key pair and I still receive the same result. Any suggestions is much appreciated!
Simplified PHP Function:
add_action('wp_ajax_get_ldap', 'get_ldap_attr');
add_action('wp_ajax_nopriv_get_ldap', 'get_ldap_attr');
function get_ldap_attr() {
header("Content-Type: application/json", true);
echo json_encode( array("happy" => "coding") );
die();
}
The jQuery:
jQuery(function() {
jQuery('#empLanId').on('blur', function () {
var lan = jQuery('#empLanId').val();
var data = { action:"get_ldap", lan:lan };
var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
}
You must send the correct content-type with your JSON response.
// Send as JSON
header("Content-Type: application/json", true);
Your updated function should look like this:
function get_ldap_attr() {
header("Content-Type: application/json", true);
echo json_encode( array("happy" => "coding") );
die();
}
See my previous answer here:
jQuery $.ajax request of dataType json will not retrieve data from PHP script

PUT with jquery returns error

I am trying to update a field with a small jquery script but it keeps returning an error and I cannot see where I have a problem.
I have an anchor with onclick="reportAd(MyAid)" that runs this:
function reportAd(aid) {
var conf = confirm("Will you report this ad?");
if(conf == true) {
$.ajax({
url: rootURL + '/reportad/',
type: 'PUT',
dataType: 'json',
contentType: 'application/json',
data: {'aid': ''+aid+''},
success: function(data) {
alert("Ad have been reported");
},
error: function(data) {
console.log(data);
}
});
}
return false;
}
Which should run this:
$app->put('/reportad/', function() use ($app, $adverts) {
$request = Slim::getInstance()->request();
$data = json_decode($request->getBody());
$adverts->report_ad($data->aid);
});
FireBug gives me this:
Object { readyState=4, status=200, statusText="OK"}
If I call the script with cURL
curl -i -X PUT -H 'Content-Type: application/json' -d '{"aid":"43"}' http://www.domain.dk/reportad/
it works.
You're asking the content of the answer to be parsed as JSON. If it's not JSON, then you're probably encountering a parseError.
Try to remove the dataType argument.
The standard approach to overcome lack of support for "PUT" is to use "POST" and to introduce a pseudo-PUT mechanism, on which the server-side code can branch.
For example :
$.ajax({
type: 'POST',
data: {method: 'PUT', 'aid': ''+aid+''},
});
Exactly what you do server-side depends on the language/framework you are using.

Categories