I have the following code written in a file name "backend_user.php"
CODE 1:
<?php
require_once '_db.php';
$json = file_get_contents('php://input');
$params = json_decode($json);
class Result {}
$response = new Result();
if ($user != null) {
$response->result = 'OK';
$response->user = $user['name'];
$response->message = 'Success';
}
else {
$response->result = 'Unauthorized';
$response->message = 'Invalid token';
}
header('Content-Type: application/json');
echo json_encode($response);
?>
The above code gets called by the code below stored in data.service.ts in Angular
CODE 2:
getUser(): Observable<any> {
return this.http.post("/api/backend_user.php", {}).pipe(map((response:any) => {
this.user = response.user;
return response;
}));
}
As you can see from above code, nothing gets passed in the request body. But in CODE 1, there is a variable named $user referred.
From where does $user get it's value from?
Can somebody clarify?
$user is just the response value. It's kind of like an arrow function in javascript so you can rename $user to $foo and do $foo['name'] and it will still work.
$user is just the given variable name for the response. So, $user['name'] is accessing HttpResonse.name effectively. name is just a property on the response.
Related
I have this class within PHP:
class Post{
public function postUser($userData){
$collection = $collection = (new MongoDB\Client('mongodb://localhost:27017'))->mydb->users;
$insertOneResult = $collection->insertOne([
"username" => $userData->username,
"email" => $userData->email,
"password"=>$userData->password,
"level"=>$userData->level,
"domainArray"=>array()
]);
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents("php://input"));
$test = new Post();
$test->postUser($data);
}
else{
header("HTTP/1.0 405 Method Not Allowed");
}
Everything works as it should, but I want to change the class name. So I changed it to the following:
class PostUser{
public function postUser($userData){
$collection = $collection = (new MongoDB\Client('mongodb://localhost:27017'))->mydb->users;
$insertOneResult = $collection->insertOne([
"username" => $userData->username,
"email" => $userData->email,
"password"=>$userData->password,
"level"=>$userData->level,
"domainArray"=>array()
]);
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents("php://input"));
$test = new PostUser();
$test->postUser($data);
}
else{
header("HTTP/1.0 405 Method Not Allowed");
}
When I do a post request with the second piece of code I get a 500 server error which indicates my code does not work anymore (on the first piece of code I get a 200 OK and everything works as it should) and then it does not work.
It has no dependencies from or to other classes which could error so I really do not have a clue where it goes wrong?
Does anyone know what I did wrong?
Change the class name to something like PostUserAction
and don't forget to change
$test = new PostUserAction();
Or change method name to postUserMethod and it should work
class foo {
function foo ($something){
echo "I see ".$something." argument";
}
}
It consider at as constructur for this class
I'm trying to understand the reason of this error message from postman when test API.
When I am testing my REST API from postman, it gives me error
ErrorException (E_NOTICE)
Trying to get property 'staff' of non-object
I try to find the problem but i can't find it. I kept searching for this but couldn't find an answer that will make this clear.
Anyone can help me on this?
Thanks!
This my code snippet
public function updatestatus($request, $leave, $is_api=0)
{
$status = $request->get('status');
$user = $is_api? JWTAuth::parseToken()->authenticate():Auth::user();
// $user = Auth::user();
$staff= $user->ref_user;
$applying_staff = $leave->staff;
$applying_user = $applying_staff->main_user;
//Approved
if($status==2 && $leave->status==1)
{
$leave->status =2;
$leave->approved_by_staff_id = $staff->staff_id;
$leave->approved_date = new Carbon('today');
$leave->save();
if($user->centre_id)
Helper::ClearObjective(10,$user->centre_id);
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr)))
->onConnection('database')
->onQueue('emails');
return response()->json(['Success'=>'Success']);
//send email
}
// Rejected
else if($status==3 && $leave->status==1)
{
$leave->status =3;
$leave->status_rejected_reason = $request->get('reason',null);
$leave->save();
if($user->centre_id)
Helper::ClearObjective(10,$user->centre_id);
$leave_cat = LeaveCategory::find($leave->leave_type);
if($leave_cat->leave_status!=0)
{
$leave_ent = $applying_staff->leaves()->where('leave_type',$leave->leave_type)->first();
if($leave_ent)
{
$leave_ent->leave_remaining += $leave->leave_days;
$leave_ent->save();
}
}
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr, $leave->status_rejected_reason)))
->onConnection('database')
->onQueue('emails');
//send email
}
//Cancelled
else if(($status==4 && $leave->status==2) || ($status==4 && $leave->staff_id == $staff->staff_id))
{
$leave->status =4;
$leave->status_rejected_reason = $request->get('reason',null);
$leave->save();
$leave_cat = LeaveCategory::find($leave->leave_type);
if($leave_cat->leave_status!=0)
{
$leave_ent = $applying_staff->leaves()->where('leave_type',$leave->leave_type)->first();
if($leave_ent)
{
$leave_ent->leave_remaining += $leave->leave_days;
$leave_ent->save();
}
}
dispatch(new EmailJob($applying_user->email,new LeaveNotification(route('staff.leave.show',$leave->id), $leave->statusStr,$leave->status_rejected_reason)))
->onConnection('database')
->onQueue('emails');
//send email
}
// return reponse()->toJson(compact('leave'));
return $leave;
}
Calling API
public function update(Request $request)
{
return $this->leaveApplicationRepository->updatestatus($request,1);
}
your updatestatus() need 3 parameter and your update() function pass only 2 paramenter;
public function update(Request $request)
{
// please provide you leave data
$leave = "your data is here";
return $this->leaveApplicationRepository->updatestatus($request,$leave, 1);
}
From the context that I can see, it is trying to reference the staff variable in:
$applying_staff = $leave->staff;
The non-object message will mean that $leave itself is the problem. Since you are passing in 1 to the call:
return $this->leaveApplicationRepository->updatestatus($request,1);
the 1 becomes the $leave parameter, and that is not an object, hence the error.
Maybe you think that by passing in 1, it will find the correct model automatically? This is not the case. You need to load that model explicitly.
Hi I have been trying to figure out how to convert an object to an array I have tried using json_decode but that doesn't turn it into a nested array but it looks like the picture below becuase I am using angular I need everything to be in an array can someone tell me what I am doing wrong
What the data currently looks like when I use json_decode
The PHP function:
public function getForm(Request $request)
{
try
{
$id = $request->input('id');
$form = admin_form::find($id);
if($form) {
$form = admin_form::where('id',$id)->with('fields')->first();
$res['Message'] = "Success";
$res['Status'] = true;
$res['results'] = json_decode($form, true);
return response($res, 200);
} else {
$res['status'] = false;
$res['message'] = "Form not found";
return response($res, 404);
}
} catch(\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}
create a variable and store json init and pass response as parameter
var test = json.parse(response);
As I know you don't need to convert object to array, cause you can iterate over it in ng-repeat. Try to use the following syntax:
<div ng-repeat="(key, val) in results">{{key}} => {{val}}</div>
According to ng-repeat documentation
Just for anyone having the problem I had this is how I sloved it
public function getForm(Request $request)
{
try
{
$id = $request->input('id');
$form = admin_form::find($id);
if($form) {
$form = admin_form::where('id',$id)->with('fields')->first();
$res['Message'] = "Success";
$res['Status'] = true;
$res['results'] = [$form->getAttributes()];
return response($res, 200);
} else {
$res['status'] = false;
$res['message'] = "Form not found";
return response($res, 404);
}
} catch(\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}
The reason this worked for me was because the $form is an object with all of the information about what I am trying to get and when you do a dd($form) all of the information that it gets from the DB is stored in the attributes array and lumen has a getAttributes() function and from there I put them into [] to get an array
But if you have a relationship with another table then don't use getAttributes just use the [] braces
I am currently trying to follow a Slim tutorial that is utilizing $app = Slim::getInstance(); I don't know much about Slim, so the solutions to use a container do not make sense to me. What can I do to make my function provided below actually run?
function jsonResponse($data, $code = 200)
{
$app = Slim::getInstance();
$app->response->setStatus($code);
$app->response->headers->set(
'Content-type',
'application/json; charset=utf-8'
);
return $app->response->setBody(json_encode($data));
}
I am calling this inside another function for logging in that looks like this:
function login($request) {
$user = json_decode($request->getBody());
$username = $user->username;
$password = $user->password;
if (empty($username) || empty($password)) {
$error = 'Username and password are required';
// Bad request
return jsonResponse($error, 400);
}
$sql = "SELECT first_name, username FROM users "
. "WHERE username = '$username' AND password = '$password'";
$db = getConnection();
$row = array();
try {
$result = $db->query($sql);
if (!$result) {
$error = 'Invalid query: ' . mysql_error();
// Internal server error
return jsonResponse($error, 500);
}
$user = $result->fetchAll(PDO::FETCH_OBJ);
if (empty($user)) {
// Unauthorized
return jsonResponse($error, 401);
}
$row["user"] = $user;
$db = null;
} catch(PDOException $e) {
error_log('{"error":{"text":'. $e->getMessage() .'}}');
// $error = array( 'error' => array ( 'text' => $e->getMessage() ) );
// Internal server error
return jsonResponse($error, 500);
}
// OK, default is 200
return jsonResponse($row);
}
My route for the login function is $app->post('/login_user', 'login');
tl;dr I would like an explanation on how to convert older Slim code that uses getInstance().
Thank you!
It's actually pretty straightforward. In this particular case you don't need jsonResponse() function at all. Your login controller will need these changes:
function login($request, $response, $args) {
// ... some code ...
if ($isError) {
return $response->withStatus(500)->withJson($error);
}
return $response->withJson($row); // Status=200 is default.
}
In general, as was said in the comments, Slim3 has no static method to get a Singleton instance. If you wanted to hook on the response object in Slim3, the best way would be to create a middleware.
Or, if you really wanted to access $response from external function, you pass it as a function parameter (respecting dependency injection pattern and keeping code testable): jsonResponse($response, $error, 500);.
Technically, $app is a global variable, but I would suggest against accessing it through $GLOBALS.
Am getting a variable called $msisdn from a view using post in one function (search_results). After doing the processing, I would like to use the same variable in another function(assign_role) currently,I am unable to do that since am getting this error
Severity: Notice Message: Undefined variable: msisdn
. Below is my search_result function where am getting the post data:
public function search_results(){
$msisdn = $this->input->post('search_data');//getting data from the view
if ($msisdn == false){
$this->load->view('add_publisher');
} else{
$this->assign_role($msisdn); //passing the variable to another function
$this->load->model('search_model');
$data['result'] = $this->search_model->search_user($msisdn);
$data1['box'] = $this->search_model->search_select($msisdn);
$result = array_merge($data, $data1);
$this->load->view('add_publisher',$result);
echo json_encode($result);
}
}
I want to use $msisdn from above function in this function below:
public function assign_role($msisdn){
//echo $msisdn['numm'];
$publisher = $this->input->post('select');
if ($publisher == false) {
$this->load->view('add_publisher');
} else {
$data = array(
'publisher' => true,
);
$this->load->model('insert_model');
$data1 = $this->insert_model->search_group($msisdn, $data);
if ($data1 == true) {
echo "Recorded updated succesfully";
$this->load->view('add_publisher');
} else {
echo "Recorded not updated";
$this->load->view('add_publisher');
}
}
}
Please help me to achieve this.
Passing variables from one function to another in the same controller can be achieved by using sessions. In Codeigniter, one can use flashdata like:
$this->session->set_flashdata('info', $MyVariable);
Remember, flashdata is only available for the next server request then it will be automatically cleared.
Then it can be retrieved as:
$var = $this->session->flashdata('info');
If you want to keep the variable for one more server request, you can do this:
$this->session->keep_flashdata('info');
Hope this will help someone faced with the problem.