json_decode(file_get_contents("php://input")) not working - php

we are creating add cart application, Trying to get property of non-object error in addremove.php file and $http is not working, $data=json_decode(file_get_contents("php://input")); are null
I am unable to connect insert the date into sql server using angularjs & php.
I want to know how to insert data in sql and fetch the data from db.
Index.js
//Include the module as a dependency of our main AngularJS app module
var app = angular.module('notesApp', [
'ngRoute'
]);
// App routing
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "home.html"
})
.when('/main/:itemn', {
templateUrl: "index1.html"
})
.when('/cart', {
templateUrl: "cart.html"
})
.when('/test', {
templateUrl: "addremove.php"
})
.when('/addremove', {
templateUrl: "addremove.php"
})
}]);
//main controller
app.controller("mainController", ['$scope', '$http', '$routeParams', '$location', '$window', function($scope, $http, $routeParams, $location, $window) {
$scope.products = [];
var arr = $location.$$path.split('/');
$scope.itemn = arr[2];
// move to new url
$scope.go = function(path) {
$location.path(path);
};
$http.get('modeldata.php').then(function(response) {
$scope.items = response.data.records;
}, function(errResponse) {
console.error('Error while fetching notes');
});
$http.get('cart.php').then(function(response) {
$scope.carts = response.data.records;
// $scope.products=$scope.items;
}, function(errResponse) {
console.error('Error while fetching notes');
});
// Add new record
$scope.addItem = function(item){
var variableName = {'a':'1'};
$http({
method: 'post',
url: 'addremove.php',
data: variableName,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
$scope.go('/test');
}
}]);
data are flow in addremove file to insert into mysql server table
// addremove.php file
<?php
$servername = "XXXXX";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXXXX";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$data = json_decode(file_get_contents("php://input"));
echo $data;
$itemno = $data->a;
$query="INSERT INTO cart(itemno) values ( '$itemno')";
if (mysqli_query($conn, $query)) {
echo 'Data Deleted Successfully...';
} else {
echo 'Failed';
}
$lastinsert_id = mysqli_insert_id($conn);
?>

It could be server cache issue. Try to clear php cache. I hope It will fix.

It could be php and server cache issue. You can clear cache and Here is another solution, we fixed same type of error in this way.
$data = json_decode(file_get_contents("php://filter"));
You need to execute this line then revert back and then try :
//It is just to check file_get_contents function is working.
$data = file_get_contents('provide_any_file.txt')
$data = json_decode(file_get_contents("php://fd"));
Now, again revert back to :
$data = json_decode(file_get_contents("php://input"));
It will clear cache in strange way.

Related

How I can get return from PHP to Ionic Controller?

This is my code. Please help me return id in PHP condition to angular controller. I get undefined in console log. This is my code. Its wrong and bad code? Thanks
My Ionic controller
.controller('LoginCtrl', function($scope, $http){
$scope.LoginUser = function(info){
console.log(info.username, info.password);
var xhr = $http.post('http://pvcm.com/api/tambah_user.php', info);
console.log(xhr);
};
})
My PHP
if(isset($data)){
$host = "";
$username_database = "";
$pass_database = "";
$database = "";
$conn = new mysqli($host, $username_database, $pass_database, $database);
$sql_petugas = "SELECT * FROM petugas WHERE id_petugas = '$data->username' AND password_petugas = '$data->password'";
$sql_masyarakat = "SELECT * FROM masyarakat WHERE id_masyarakat = '$data->username' AND password_masyarakat = '$data->password'";
//$hasil = mysql_num_rows($sql);
$hasil_petugas=mysqli_query($conn, $sql_petugas);
$hasil_masyarakat=mysqli_query($conn, $sql_masyarakat);
$count_petugas = mysqli_num_rows($hasil_petugas);
$count_masyarakat = mysqli_num_rows($hasil_masyarakat);
if($count_petugas > 0){
return json_decode('id'=>100);
}else if($count_masyarakat > 0){
return "masyarakat ketemu";
}
$qry = $conn->query($sql);
$conn->close();
}
?>
On the Ionic side you are missing the promise. The $http returns a promise, not the data itself, that means that you have to use another function to get the data. Like this:
.controller('LoginCtrl', function($scope, $http){
$scope.LoginUser = function(info){
console.log(info.username, info.password);
var xhr;
$http.post('http://pvcm.com/api/tambah_user.php', info)
.then(function(phpData){
xhr = phpData;
})
.catch(function(error){
xhr = error;
});
console.log(xhr);
};
})
Here, the function inside .then() executes if the request was successfull and gets the data in the phpData parameter, and the .catch() excecutes if the request was an error (404, 500, etc).
In the PHP code I think you have to print the result instead of returning it. Like echo json_decode('id'=>100);

Why my ajax function does not work on yii2

Hello *** please How can i use ajax function in yii2
in fact I am working on a product of this framework(yii2), not on it directly, But I think it's the same principle. and i want to draw charts (chartJs or googleChart or d3 ... anyway)
so in index file of backend area (xx/xx/xx/dashboard/index.php) I want to send an ajax request to an another php file (simple and logical)
this one is placed in the same folder as index (xx/xx/xx/dashboard) , but nothing happens ! :(
I notice that if I test my two files (indexAjax and phpDB) outside framework folders I get a nice result
but once it's has within framework files, they will no longer work :(
my code is as follows :
1/ part of my index file
<canvas id="mycanvas" width="400" height="400"></canvas>
<script>
$(function()
{
$.ajax({
url: "chartData.php",
type:'POST',
data:{'trigger':'trigger'},
success: function(data) {
alert(data);
console.log(data);
var idTab = [];
var resultatTab = [];
for(var i in data) {
idTab.push("data " + data[i].id);
resultatTab.push(data[i].resultat);
}
var chartdata = {
labels: idTab,
datasets : [
{
label: 'Player Score',
backgroundColor: 'deepskyblue',
borderColor: 'dodgerblue',
hoverBackgroundColor: 'orange',
hoverBorderColor: 'yellow',
data: resultatTab
}
]
};
var ctx = $("#mycanvas");
var doughnutGraph = new Chart(ctx, {
type: 'doughnut',
data: chartdata,
options:{responsive:false}
});
},
error: function(data) {
alert(JSON.stringify(data));
console.log(data);
}
});
}); // fin jQuery
</script>
2/ the 2nd file (php)
<?php
if (isset($_POST['trigger']))
{
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'lab');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT * FROM score");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
}
NB: I must also say that I did not respect the principle of the MVC
i put everything in a same folder ... but I think it's still a choice
thanks a lot
I think you have to look how the routing in yii2 works
http://www.yiiframework.com/doc-2.0/guide-structure-overview.html
or here
http://www.yiiframework.com/doc-2.0/guide-start-hello.html
you can not directly call an php file ..
for example, in javascript:
$.get('/site/user-messages', function (data, status) {
if (status !== 'success') {
console.log('ERROR: '+ status);
return;
}
allData = JSON.parse(data);
});
here site is the controller and user-messages is the action
in this case the prettyUrl mode is enabled in urlManager
Add the content of you charData.php files in a proper action eg: inside siteController.php
public function actionChartData() {
your code
.........
return $this->render('your_related_view', [
/* your vars */
'my_var' => $my_var,
]);
}
the call the action i ajax using
$.ajax({
url: <?php echo \yii\helpers\Url::to(['/site/chart-data']) ?>,
type:'POST',
data:{'trigger':'trigger'},
success: function(data) {
........

Problems populating a select list with angular js and php

I am trying to populate a select list with data from my db (php & mysql). I am working with AngularJs and Angular Material. So for i am not able to show the data from the db in the list
db situation:
tblProjectType -> name of table
2 rows:
id_ProjectType
project_type
Any help or pointers would be great.
This is my html code:
<form ng-controller="AppCtrl">
<div layout="row">
<md-select-label>Project type</md-select-label>
<md-select ng-model="project_type" name="project_type" placeholder="Choose a project type" id="containerProjectType">
<md-option ng-repeat="projecttype in projecttypes" value="{{projecttype.id_ProjectType}}">{{projecttype.project_type}}</md-option>
</md-select>
</div>
</form>
The code of my app.js is:
var app = angular.module("DragDrop", ['ngMaterial']);
app.controller('AppCtrl', function($scope, $mdDialog, $http) {
$scope.projectTypeInfo = [];
var getProjectTypeFunction = function(succesFn, errorFn)
{
$http.get('db.php?action=get_ProjectType_info')// call to the server
.succesFn(function(data){
succesFn(data); //call the function passed into getProjectTypeFunction with the data from the server
console.log('Retrieved data from server');
})
.error(errorFn || function() {
console.log("Error in retrieving data from server");
})
}
this.reloadProjectTypeList = function()
{
getProjectTypeFunction(
/* success function */
function(data) {
//debugger;
$scope.projectTypeInfo = data;
//digest recycle
//if (!$scope.$$phase) { $scope.$apply(); }
},
/* error function */
function()
{
alert("Server load failed");
})
};
My php code is:
<?php
include('config.php');
//echo ('test' . $_GET['action']);
switch($_GET['action']) {
case 'get_ProjectType_info' :
get_ProjectType_info();
break;
}
/** Function to data from tblProjectType **/
function get_ProjectType_info(){
$qry = mysql_query('SELECT * from tblProjectType');
echo("test");
//echo(qry);
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id_ProjectType" => $rows['id_ProjectType'],
"project_type" => $rows['project_type']
);
}
print_r(json_encode($data));
return json_encode($data);
}
?>
So for starters lets clean up your JS. We can reduce what you have to this:
var app = angular.module("DragDrop", ['ngMaterial']);
app.controller('AppCtrl', function($scope, $mdDialog, $http)
{
$scope.projectTypeInfo = [];
$scope.getProjectTypeFunction = function()
{
$http.get('db.php?action=get_ProjectType_info')
.success(function(data, status, headers, config)
{
$scope.projectTypeInfo = data;
console.log('Retrieved data from server');
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log("Error in retrieving data from server");
console.log(data,status);
});
};
$scope.getProjectTypeFunction(); //-- call the function that invokes $http.get()
};
In PHP your function needs to echo the data via echo json_encode($data);, not return it (as stated by #Avalanche).
Now, your console should output something, but you need to remove console.log("test"); from your PHP as that will surely cause an error.
edit
Currently your repeat states:
<md-option ng-repeat="projecttype in projecttypes" value="{{projecttype.id_ProjectType}}">{{projecttype.project_type}}</md-option>
We have stored your data in $scope.projectTypeInfo therefore it needs to be modified to:
<md-option ng-repeat="projecttype in projectTypeInfo" ng-value="projecttype.id_ProjectType">{{projecttype.project_type}}</md-option>

Posting data with AngularJS, PHP and MySQL

I want to store an image as a blob into my database(MySQL) while using PHP Rest service, but I dont know how to do it. Here is my PHP code (I'm using Slim framework for PHP)
function addProblem() {
global $app;
$postdata = file_get_contents("php://input");
$req = json_decode($postdata); // Getting parameter with names
$paramName = $req->station; // Getting parameter with names
$paramAdres = $req->address; // Getting parameter with names
$paramCity = $req->city;// Getting parameter with names
$parampostal = $req->postalcode;
$parampic = $req->pictureOfDamage;
$paramdescrip= $req->description;
$sql = "INSERT INTO problems (Station,Address,Postalcode,City,PictureOfDamage,Description) VALUES (:station,:address,:postalcode,:city,:pictureOfDamage,:description)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam(':station', $paramName);
$stmt->bindParam(':address', $paramAdres);
$stmt->bindParam(':city', $paramCity);
$stmt->bindParam(':postalcode', $parampostal);
$stmt->bindParam(':pictureOfDamage', $parampic);
$stmt->bindParam(':description', $paramdescrip);
$stmt->execute();
$dbCon = null;
echo json_encode("toegevoegd ");
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this is my angular code (i'm using fileuploader right now.)
.controller('MeldingController', function ($scope, $upload, $rootScope, $state, $http) {
$scope.station = $rootScope.station;
$scope.PictureOfDamage;
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var pictureOfDamage = files[i];
return pictureOfDamage;
}
}
}
$scope.submit = function () {
console.log($scope.PictureOfDamage);
var data = {
station: $scope.station.name,
address: $scope.station.streetName,
postalcode: $scope.station.postalCode,
city: $scope.station.city,
pictureOfDamage: $scope.upload($scope.files) /* picture*/,
description: document.getElementById("Description").value
}
console.log('NOJSN ', data);
data = JSON.stringify(data);
console.log('JSON', data)
$http({
method: "POST",
url: 'http://localhost/Dats24/problem/add/',
data: data})
.success(function (data, status, headers, config) {
$state.go('GoogleMaps');
}).error(function (data, status, headers, config) {
console.log(data);
});
};
})
For your angular application, you can use the upload method of the $upload service like this:
file_upload: function(file) {
return $upload.upload({
url: 'http://your-upload-url/',
file: file
});
}
as described in here : https://github.com/danialfarid/ng-file-upload
Then on your service in PHP, you can get the file using
move_uploaded_file($_FILES['file']['tmp_name'], $file_path);
It will store the file on the path of your choice, then you can use PHP to do whatever you want with the file data.

Why is this jquery ajax call not returning data from my php script?

I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});

Categories