I am using angularjs 1.6.4 version, I send my keys and values to php web service but my key and value does not read, I get result for in database stored at '0', this is my angular js code,
$scope.fav = {
"userid":101,
"favid":120
}
$http({
method:"POST",
url:apiurl+"addFavorites.php",
data:JSON.stringify($scope.fav)
}).then(function(data)
{
$scope.favorites = data.data;
alert(data.data.message);
});
this is my php rest api
include("../includes/db.php");
//creating response array
$response = array();
$request_method = $_SERVER['REQUEST_METHOD'];
if ($request_method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
$request_method = 'DELETE';
} else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
$request_method = 'PUT';
} else {
throw new Exception("Unexpected Header");
}
}
if($request_method == "POST"){
//getting values
$userid = isset($_POST['userid']) && $_POST['userid'] != '' ? trim($_POST['userid']) : "";
$favid = isset($_POST['favid']) && $_POST['favid'] != '' ? trim($_POST['favid']) : "";
if ($favid == 0) {
$strupdate = mysql_query("insert into nr_favourites(UserProfileId,FavouriteUserProfileId,CreatedDate)Values('$userid','$favid',now())");
}
if ($favid != 0) {
$sql = mysql_query("select * from nr_favourites where id=$favid");
$rc = mysql_num_rows($sql);
if ($rc != 0) {
$strupdate = mysql_query("insert into nr_favourites(UserProfileId,FavouriteUserProfileId,CreatedDate)Values('$userid','$favid',now())");
}
}
if ($strupdate)
{
$response['error']=false;
$response['message']='add favourites successfully!';
}
else
{
$response['error']=true;
$response['message']='add favourites not successfully.';
}
} else {
$response['error']=true;
$response['message']='You are not authorized';
}
header('Content-Type: application/json');
echo json_encode($response);
those are my code, please help me to solve this error
It looks like you may be saving strings to numerical fields. When JSON.stringify($scope.fav) is called the numbers are converted to strings.
Here
$userid = isset($_POST['userid']) && $_POST['userid'] != '' ? trim($_POST['userid']) : "";
$favid = isset($_POST['favid']) && $_POST['favid'] != '' ? trim($_POST['favid']) : "";
since user_id and favid are strings they are set to empty strings every time. My guess would be both
nr_favourites.UserProfileId
nr_favourites.FavouriteUserProfileId
are numerical fields which are receiving strings hence the 0 values. Remove JSON.stringify() and save nulls rather than empty strings, this should take care of the issue.
Related
my table field status is NULL[default], or it is 0, or 1. then i assign to PHP var $status. when value is NULL i want to display no icon, when value is 0, display a gray check image, when value is 1, display a green check image.
trouble is, NULL value shows a gray check image, 0 does not show a check image. somehow NULL and 0 are alike but only in one direction. what i mean is, regardless of how i conditionally test if var is null, not null, null but not zero, they get interpreted wrongly. it is confusing. there must be a simple straight foward way to keep NULL and 0 separate and distinct. i grab the value:
$status = $Card['status']; //from above array.
if ($status == 1) {
$status = '1';
} else if ($status == 0) {
$status = '0';
} else if ($status === NULL) {
$status = 'NULL';
}
then to display the images either gray, green, or none at all i am trying this:
if ($status == '1') {
echo "<img src='../images/status_check_green.png' />";
} else if ($status == '0') {
echo "<img src='../images/porc_check_gray.png' />";
} else if ($status == 'NULL') {
echo "<img src='' />";
}
}
i know i do not need the '' around the values, but i am trying to literalize everything to force valid comparisons. likely no need for someone to try unraveling my code; but to elucidate how to keep NULL and 0 separate. it's like i am missing something fundamental here. btw, when i stuff a js var with the PHP var, it gets the correct value; they just don't follow the comparison like i need them to.
ideas?
HI your issue is procedure order or not type checking the 0 ( depending if you want to catch false )
if ($status == 1) {
$status = '1';
} else if ($status == 0) {
$status = '0'; //<--- this runs on null because (null == 0) is true
} else if ($status === NULL) {
$status = 'NULL'; //<--- this block is un-reachable
}
Because your not type checking with === of 0 null will return true for that condition.
See this sandbox with and example using $status = null;
http://sandbox.onlinephpfunctions.com/code/1f3dd9d83d0026aa0f682b61bed2ba858ae285aa
Outputs:
'0'
If you change it to this
if ($status == 1) {
$status = '1';
} else if ($status === 0) {
$status = '0';
} else if ($status === NULL) {
$status = 'NULL';
}
As you can see here using the same setting for $status
http://sandbox.onlinephpfunctions.com/code/d86b0c60c06338d2d6ee1c1fa9d3fa7e08a22663
Outputs
'NULL'
The other way to fix it would be to switch them so the more specific one is first.
if ($status == 1) {
$status = '1';
} else if ($status === NULL) {
$status = 'NULL';
} else if ($status == 0) { //I would prefer if(!$status){ but I'm lazy
$status = '0';
}
Then 0 would catch false as well as 0 but not null as the block above it will catch it first. You can see this last one here
http://sandbox.onlinephpfunctions.com/code/3028f5826dcede29b14dd8cfc03618ea5830c12c
Which also outputs
'NULL'
Cheers!
I have a Pass for Apple Wallet with a webServiceURL specified which I am currently trying to get working. So far, I can tell if the pass is added or deleted, after verifying with Auth Token and I get the correct Device ID as well as Serial Numbers. However, the value of $_POST is an empty array when the pass is added, so I cannot get the Push Token. Is there something I am missing? Here is my PHP.
<?php
function unauthorized() {
header('HTTP/1.1 401 Unauthorized');
exit;
}
$headers = apache_request_headers();
if (isset($headers['Authorization']) && strpos($headers['Authorization'], 'ApplePass') === 0 && strpos($_SERVER['PATH_INFO']) !== false) {
$pathInfo = $_SERVER['PATH_INFO'];
if ($pathInfo[0] === '/') { $pathInfo = substr($pathInfo, 1); }
$parameters = explode('/', $pathInfo);
if ($parameters[0] !== 'v1' || $parameters[1] !== 'devices' || $parameters[3] !== 'registrations' || $parameters[4] !== 'MYPASSIDENTIFIER') {
unauthorzed();
exit;
}
$deviceId = $parameters[2];
$passSerial = $parameters[5];
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// User deleted pass
} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// User added pass
$payload = json_decode($_POST);
// $_POST is empty array, and $payload is always nothing
} else {
// Something fishy
unauthorized();
}
} else {
unauthorized();
}
Try using the REQUEST_URI and read the body with php://inpupt
$headers = apache_request_headers();
$request = explode("/", substr(#$_SERVER['REQUEST_URI'], 1));
if (strtoupper($_SERVER['REQUEST_METHOD']) === "POST"
&& isset($headers['Authorization'])
&& (strpos($headers['Authorization'], 'ApplePass') === 0)
&& $request[1] === "devices"
&& ($request[3] === "registrations") {
$auth_key = str_replace(array('ApplePass '), '', $headers['Authorization']);
$device_id = $request[2];
$pass_id = $request[4];
$serial = $request[5];
$dt = #file_get_contents('php://input');
$det = json_decode($dt);
// Process Device Token
I tried to run the code below but it doesn't work, and I tried everything I remember and couldn't get to work.
AJAX Call
var status = $(this).prop("checked");
var room_id = id;
$.post('maintenanceControl.php', {action: status, id: room_id});
PHP Script
<?php
if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
$action = $_POST['action'];
$id = $_POST['id'];
if ($action) {
return manageMaintenance($id, true);
} else {
return manageMaintenance($id, false);
}
}
function manageMaintenance($room_id, $status)
{
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString, true);
foreach ($data['rooms'] as $key => $entry) {
if ($key == $room_id) {
$data[$key]['maintenance'] = $status;
}
}
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
return true;
}
At first I thought it was a malfunction but the example below worked just fine
$.post( "test.php", function( data ) {
alert(data);
});
PHP
<?php
echo "test";
In order to get data back into the Javascript ajax call, you need the php script to echo something.
Return values in php do not find their way back into the Ajax call.
Often, php scripts echo a value, either a single value or if you want the get more complex data from php back into the Ajax call, you can json encode several values and echo that.
You have to echo/print something in php script to send response to ajax request. You have to do something like below.
$response=false;
if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
$action = $_POST['action'];
$id = $_POST['id'];
if ($action) {
$response=manageMaintenance($id, true);
} else {
$response=manageMaintenance($id, false);
}
}
function manageMaintenance($room_id, $status)
{
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString, true);
foreach ($data['rooms'] as $key => $entry) {
if ($key == $room_id) {
$data[$key]['maintenance'] = $status;
}
}
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
return true;
}
echo $response==true? "OK" : "FAILED";
I made this function to check for expected request variables. It was working great until I realized that if two values (Not keys) were the same, it would return a positive number as though a key was missing. Consider the following code:
function requestCheck($expectedAr)
{
if(isset($_GET) && isset($_POST))
{
$requestAr = array_unique(array_merge($_GET, $_POST));
}elseif(isset($_GET)){
$requestAr = $_GET;
}elseif(isset($_POST)){
$requestAr = $_POST;
}else{
$requestAr = array();
}
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0)
{
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
if 'name' and 'password' both hold the same value, it will run returnError(). Not seeing why.
Here's a dump of $_POST:
array (
'poolName' => 'xpool',
'userPrefix' => 'xpool'
)
array_unique will strip unique values so you'll end up with either name or password but not both.
Solution:
function requestCheck($expectedAr) {
if(isset($_GET) && isset($_POST)) {
$requestAr = $_REQUEST;
}elseif(isset($_GET)) {
$requestAr = $_GET;
}elseif(isset($_POST)) {
$requestAr = $_POST;
}else{
$requestAr = array();
}
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0)
{
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
I think it's safe to also do the following:
function requestCheck($expectedAr) {
$requestAr = isset($_REQUEST) && is_array($_REQUEST)?$_REQUEST:array();
$diffAr = array_diff_key(array_flip($expectedAr),$requestAr);
if(count($diffAr) > 0) {
returnError("Missing variables: ".implode(',',array_flip($diffAr)).".");
}else {
return $requestAr;
}
}
$requestAr = requestCheck(['name','password']);
how to count numerical character combine with string character in php? if i use strlen, thats only count string. I want limit username input value only 20 character, if i input 20 or more string only, this code work, but if i input (e.g : Admin123Admin123Admin123) thats not work, my validation input fail.
i have a code in yii 2 useraccount controller like this :
// new user
if ( $username != '' && $password != '' && intval($group) > 0 && !$exist)
{
$myFunctions = new userFunctions;
$exist = $myFunctions->isUserNameExist( $username );
$isValid = $myFunctions->isValidPassword( $password );
$checkUsername = strlen($username);
// $temp = str_split($username); // Convert a string to an array by each character
// // if don't want the spaces
// $temp = array_filter($temp); // remove empty values
// $checkUsername = count($temp);
if ( $isValid == 0 && !$exist)
{
$result = $myFunctions->saveNewUser( $username, $password, $group, $expired );
$error = ( $result ) ? 0 : 1;
}
else if( $exist )
{
$error = 3;
}
else $error = 2;
}
}
echo \yii\helpers\Json::encode(['result' => $result, 'error' => $error, 'checkUsername' => $checkUsername ]);
this is my code in view :
function saveNewUsers()
{
$.ajax({
type :'POST',
dataType : 'json',
data : { id: $('#hiUserID').val(), username : $('#txtUsername').val(), password: $('#txtPassword1').val(), group: $('#cbUserGroup').val(), expired: $('#cbExpired').val() },
url : '" . \Yii::$app->getUrlManager()->createAbsoluteUrl('useraccount/saveuser') . "',
success : function(response) {
if ( !response.result ) {
if ( response.error == 2 )
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[20]}.')).show();
}
else if( response.error == 3 )
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[56]}.')).show();
}
else if( response.checkUsername > 20)
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[57]}.')).show();
}
else $('#errorMessageUser').html(DecodeEntities('{$myLabels[22]}.')).show();
}
else {
$('#errorMessageUser').html('').hide();
$('#myUserModal').modal('hide');
$.pjax.reload({container:'#myPjax',timeout:false});
}
}
});
}
so, how to count numerical and string in php? i am really new in php thanks for helping and i hope suggestion from our programmers here. Sorry for my bad English.
i already found the answer, yes thanks for chris 85, strlen is not problem but the problem is in controller, this is i change my code :
if ( $username != '' && $password != '' && intval($group) > 0 && !$exist)
{
$myFunctions = new userFunctions;
$exist = $myFunctions->isUserNameExist( $username );
$isValid = $myFunctions->isValidPassword( $password );
$checkUsername = strlen($username);
// var_dump($checkUsername); die();
if ( $isValid == 0 && !$exist && $checkUsername <= 20)
{
$result = $myFunctions->saveNewUser( $username, $password, $group, $expired );
$error = ( $result ) ? 0 : 1;
}
elseif ($checkUsername > 20 )
{
$error = 99;
}
else if( $exist )
{
$error = 3;
}
else $error = 2;
}
and in the view like this :
function saveNewUsers()
{
$.ajax({
type :'POST',
dataType : 'json',
data : { id: $('#hiUserID').val(), username : $('#txtUsername').val(), password: $('#txtPassword1').val(), group: $('#cbUserGroup').val(), expired: $('#cbExpired').val() },
url : '" . \Yii::$app->getUrlManager()->createAbsoluteUrl('useraccount/saveuser') . "',
success : function(response) {
if ( !response.result ) {
if ( response.error == 2 )
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[20]}.')).show();
}
else if( response.error == 3 )
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[56]}.')).show();
}
else if( response.error == 99)
{
$('#errorMessageUser').html(DecodeEntities('{$myLabels[57]}.')).show();
}
else $('#errorMessageUser').html(DecodeEntities('{$myLabels[22]}.')).show();
}
else {
$('#errorMessageUser').html('').hide();
$('#myUserModal').modal('hide');
$.pjax.reload({container:'#myPjax',timeout:false});
}
}
});
}
thanks for helping, finally i get the answer.