I have a set up that I require a count on a collection, I just keep getting an error of
{"status":false}
My model looks like:
public function count_users() {
$query = $this->mongo_db->get('users');
$row_count = count($query);
$data = $row_count;
$return = [
'status' => true,
'data' => $data
];
}
and my controller is such :
// **
// ** List Todays Stats for Admin Panel
// **
public function todaysstats_get() {
//Validate user - logged in as admin -- session required
$this->session_model->check_session();
//Count Users
$data = $this->admin_model->count_users();
$http = $this->data_model->status_to_http_response($data['status']);
$data['status'] = $http['status'];
$http_response = $http['http_response'];
$this->set_response($data, $http_response);
}
I'm using a GET method to get the simple count return number
$route['v1/admin/todaysstats'] = 'v1/admin/todaysstats';
I have tried a few different ways but it just doesn't seem to change the status on the REST request.
The method for $http = $this->data_model->status_to_http_response($data['status']);
public function status_to_http_response($status) {
// Select appropriate HTTP Response code, based on "status"
// true ---> 200
// false ---> 422 (usually a validation error)
// else ---> use the value in "status" and set "status" to false.
$status = intval($status);
// If "true" send back a 200
if ($status == 1) {
$http = REST_Controller::HTTP_OK;
$status = true;
}
// If "false" send back a 422
elseif ($status == 0) {
$http = REST_Controller::HTTP_UNPROCESSABLE_ENTITY;
$status = false;
}
// Otherwise use the status code given
else {
$http = $status;
$status = false;
}
return [
'http_response' => $http,
'status' => $status,
];
}
Related
I have a little problem with authorize.net and yiiframework
I need to create a customer account in authorize.net system with data from my webiste with api.
I'm using this extension https://www.yiiframework.com/extension/authorize-net-cim-yii-extension , but without success.
Share with you what I'm trying to do
ajax return is with code 500
The variable error should return error or success, but actually return nothing
thanks in advance
$userInfo = [
'type' => 'Payment', //Payment OR Withdraw
'user_id' => 12314,
'profile_id' => 1231231,
'email' => $this->data['email_address'],
];
echo Yii::app()->authorizenetCIM->authNetCreateProfile($userInfo);
// $result = Yii::app()->authorizenetCIM->authNetCreateProfile($userInfo);
if ($result != "error") {
$this->msg = t("success");
return ;
} else {
$this->msg=t("error");
return ;
}
public function authNetCreateProfile($data) //$type = Payment OR Withdraw
{
//build xml to post
$content =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
"<createCustomerProfileRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">" .
$this->getMerchantAuthenticationBlock().
"<profile>".
"<merchantCustomerId>" . CHtml::encode(strip_tags($data['type']))."-".CHtml::encode(strip_tags($data['user_id']))."-".CHtml::encode(strip_tags($data['profile_id'])) ."</merchantCustomerId>". // Your own identifier for the customer.
"<description></description>".
"<email>" . CHtml::encode(strip_tags($data['email'])) . "</email>".
"</profile>".
"</createCustomerProfileRequest>";
$response = $this->sendXMLRequest($content);
$parsedresponse = $this->parseAPIResponse($response);
if ("Ok" == $parsedresponse->messages->resultCode) {
return htmlspecialchars($parsedresponse->customerProfileId);
}
return "error";
}
I've written a simple api which lets me get the data from my database in an organised way. www.example.com/api/get/all gives me all the data from one table in the database as an array, encodes it as json and then echos it. This is used by a file which is called as a CRON job every day and dumps it (and some other data) to a .js file which the website front-end uses.
Strangely, if I go to www.example.com/api/get/all it runs for about 2-3 minutes (there is a lot of data in that table) and then outputs nothing to the screen. However, if I add an echo to the function before it loops through all the data, I get the json encoded data string outputed to the screen. Has anybody come across this before? Is it a bug? Is there a workaround?
It seems very strange that it will only echo after there has been an echo/print.
Here is the parts of my api that are relevant:
// ENDPOINT people:
private function candidates()
{
$response = new stdClass();
// Fetch all users:
if( $this->verb == 'all' )
{
// Get everyone from the DB:
$sql = $this->_db->query( 'SELECT id FROM ff_candidates' );
if( $sql )
{
$candidates = array();
while( $obj = $sql->fetchObject() )
{
// var_dump($obj);
$candidate = new Candidate( $this->_db, $obj->id );
$person = new stdClass();
// Start the response:
$person->id = $candidate->get_id();
$person->name = utf8_encode($candidate->get_name());
$person->gender = $candidate->get_gender();
$candidates[] = $person;
}
$this->_response( $candidates );
}
else
{
$response->success = false;
$response->message = 'There was a problem fetching the candidate. Please try again.';
$this->_response( $response, 500 );
}
}
}
// Send a response to the server:
private function _response( $response, $status = 200 )
{
$verbose = $this->_requestStatus( $status );
header("Content-Type: application/json");
header( 'HTTP/1.1 '.$status.' '.$verbose );
if( is_string($response) )
{
$data = new stdClass();
$data->message = $response;
$data->status = $status;
$data->title = $verbose;
}
else
{
$data = $response;
}
$json = json_encode( $data );
echo $json;
exit();
}
EDIT:
_requestStatus() code:
private function _requestStatus( $code )
{
$status = array(
200 => 'OK',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
429 => 'Too Many Requests',
500 => 'Internal Server Error',
503 => 'Service Unavailable',
);
return ( $status[$code] ) ? $status[$code] : $status[500];
}
I'm new with Slim framework. I want to know how to return response with the body and status code as I wish. For now, it only performs as I wish if the query returns records, but not if the query failed (e.g. select * from notexiststable) or returns nothing and with Firefox I see the status is 204 in both cases.
So here's the code:
$app->get('/models', function (Request $request, Response $response) {
$conn = getConnection();
$result = pg_query($conn, "SELECT * FROM model where m_id = 2;"); //this will return 0 record!
if (!$result) {
$data = array("Error Message" => 'Query did not execute successfully');
$newResponse = $response->withJson($data, 500);
}
else {
if (pg_num_rows($result) == 0) {
$data = array("Warning Message" => "There's no existent Model!");
$newResponse = $response->withJson($data, 204);
}
else {
$data = array();
while ($row = pg_fetch_assoc($result)) {
$data['Models'][] = $row;
}
$newResponse = $response->withJson($data, 200);
}
}
return $newResponse;
});
Thank you in advanced!
Status code 204 is No Content and the HTTP specification notes that there cannot be a body in the message.
Change the status code for your error to an error code, such as 400.
ie. Change:
if (pg_num_rows($result) == 0) {
$data = array("Warning Message" => "There's no existent Model!");
$newResponse = $response->withJson($data, 204);
}
to:
if (pg_num_rows($result) == 0) {
$data = array("Warning Message" => "There's no existent Model!");
$newResponse = $response->withJson($data, 400);
}
and the JSON will be sent to the client.
I am using this function to check all required parameters are available or not in request before processing user request.
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}
Usage is like this:
$app->post('/tasks', function() use ($app) {
// check for required params
verifyRequiredParams(array('task'));
// if OK process request.
});
function works fine if post data is of form type. like this: mobile=1234567880&otp=123456
Now i am changing the code to accept form data of JSOn type. like this: {"mobile":"0000000000","otp":"970996", "items":[{"pid":"12", "vid":"20", "pname":"amul"},{"pid":"13", "vid":"2", "pname":"dmul"}]}
This is how i am getting data.
$app->post('/tasks', function() use ($app) {
$data = json_decode(file_get_contents('php://input'), true);
$mobile = $data["mobile"];
// check for required params
verifyRequiredParams(array('task'));
// if OK process request.
});
What changes should i do now in verifyRequiredParams() to check for required params in case of JSON post data?
I suggest you don't access PHP superglobals (like $_REQUEST) in your verify method. The verifyRequiredParams should not really interfere in your application flow, but just verify the parameters and return an appropriate response. Something like this:
function verifyRequiredParams($required_fields, $request_params) {
$error = false;
$error_fields = array();
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields[] = $field;
}
}
if ($error) {
// Required field(s) are missing or empty
return array(
'error' => true,
'message' => 'Required field(s) ' . implode(', ', $error_fields) . ' is missing or empty'
);
}
// return appropriate response when successful?
return array(
'success' => true
);
}
Depending on how your data is being submitted, you pass the appropriate array into the verify method. Here are some examples:
// directly pass in the request superglobal (for GET, POST)
$response = verifyRequiredParams(array('task'), $_REQUEST);
// or deal with PUT data
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
$response = verifyRequiredParams(array('task'), $request_params);
}
// or deal with json encoded data
$data = json_decode(file_get_contents('php://input'), true);
$response = verifyRequiredParams(array('task'), $data);
Since the verifyRequiredParams now returns a response, you'll have to deal with this externally, for example:
$response = verifyRequiredParams(array('task'), $request_params);
if(isset($response['error'])){
$app = \Slim\Slim::getInstance();
echoResponse(400, $response);
$app->stop();
}
Removing superglobals and logic that ties into your application-flow from the validating method will make it easier to reuse.
I have Yii radio button list as follows.
forgotpassword1.php
<?php echo $form->radioButtonList($model, 'send_option', $email_exist); ?>
This is the action for forgotpassword1.
public function actionForgotpwd2() {
$model = new User;
$email_exist = array('mobile' => 'Send SMS to Mobile');
$model -> setScenario('forgotpwd2');
$model -> send_option='mobile';
$postvars = array('conn' => Yii::app()->session['mobile']);
$postRes = SCAppUtils::getInstance()->post_request('accounts', 'CheckAccount', $postvars);
$out_arr = json_decode($postRes, true);
//print_r($out_arr);
if ($out_arr['success'] == true && $out_arr['email'] == true) {
$email_exist['email'] = 'Send an E-mail';// = array('mobile' => 'Send SMS to Mobile', 'email' => '');
} else if ($out_arr['success'] == false) {
Yii::app()->user->setFlash('error', $out_arr['error']);
$this->redirect(array('forgotpwd1'));
}
if (!empty($_POST['User'])) {
$model->attributes = $_POST['User'];
echo Yii::app()->session['mobile'];
//print_r($_POST);
if(isset($_POST['User']['send_option'])) {
//Yii::app()->session['send_option'] = $model->send_option;
echo Yii::app()->session['send_option'];
$postvars = array('conn' => Yii::app()->session['mobile'], 'send_type' => $model->send_option);
$postRes = SCAppUtils::getInstance()->post_request('accounts', 'ChangePassword', $postvars);
$out_arr = json_decode($postRes, true);
// print_r($out_arr);
if ($out_arr['success'] == true) {
$this->redirect(array('forgotpwd3'));
} else {
Yii::app()->user->setFlash('error', $out_arr['error']);
}
}
}
$this->render('forgotpwd2', array(
'model' => $model, 'email_exist' => $email_exist
));
}
Here I call a function named "ChangePassword()" from my backend application. One of the parameters passed to the backend is send_type: mobile or email. The problem is it will always takes mobile as the send_type.
I've used
$model -> send_option='mobile';
to set the default value as mobile.
Why it always takes mobile as the send type.
Any suggestions are appreciated.
Thank you in advance
Try with this :
<?=$form->radioButtonList($model,'send_option',array(1=>'Mobile',2=>'Email'))?>
In your Acion :
To set the default value :
$model -> send_option=1;
To get the checked value (check whether it's 1 or 2) :
$_POST['send_option']