How to send a post request to the RESTserver api in php-Codeigniter?
Asked Answered
K

2

8

I've been trying to make a POST request in my CodeIgniter RestClient controller to insert data in my RestServer, but seems like my POST request is wrong.

Here is my RestClient POST request in controller:

$method = 'post';
$params = array('patient_id'      => '1',
                'department_name' => 'a',
                'patient_type'    => 'b');
$uri = 'patient/visit';
$this->rest->format('application/json');
$result = $this->rest->{$method}($uri, $params);

This is my RestServer's controller: patient

function visit_post()
{
    $insertdata=array('patient_id'      => $this->post('patient_id'),
                      'department_name' => $this->post('department_name'),
                      'patient_type'    => $this->post('patient_type') );

    $result = $this->user_model->insertVisit($insertdata);

    if($result === FALSE)
    {
        $this->response(array('status' => 'failed'));
    }
    else
    {
        $this->response(array('status' => 'success'));
    }
}

This is user_model

public function insertVisit($insertdata)
{
   $this->db->insert('visit',$insertdata);
}
Komi answered 12/12, 2014 at 9:7 Comment(4)
Please specify your question. What does not work, what is the error etc...Tithable
@Tithable I've been trying to make a POST request in my CodeIgniter RestClient controller to insert data in my CodeIgniter RestServer, but it never inserts data in my database.Komi
Do you receive the value from $this->response? If so, you could output the post. $this->response(array($_POST))Examinee
no..i dont get any value. i feel my RestClient POST request is wrong.Komi
K
14

Finally I came up with a solution, I used PHP cURL to send a post request to my RESTserver.

Here is my RESTclient POST request

 $data = array(
            'patient_id'      => '1',
            'department_name' => 'a',
            'patient_type'    => 'b'
    );

    $data_string = json_encode($data);

    $curl = curl_init('http://localhost/patient-portal/api/patient/visit');

    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
    );

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // Make it so the data coming back is put into a string
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);  // Insert the data

    // Send the request
    $result = curl_exec($curl);

    // Free up the resources $curl is using
    curl_close($curl);

    echo $result;
Komi answered 13/12, 2014 at 5:55 Comment(0)
M
0

you may debug your code. try to print Global variable $_POST. and I think this may solve your problem just use $this->input->post instead of instead of $this->post

Mucous answered 12/12, 2014 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.