0

I am trying to create a simple calculator that will perform calculation by unitary method

Below is my controller

class Calculator extends CI_Controller {

function __construct(){
    parent::__construct();


    $this->load->helper('url');
}

    public function index()
    {
        $mid_cal = 0;
        $total_cost = 0;
        $this->load->view('Calculator',$total_cost,$mid_cal);
        //print_r($total_cost);

    }

    public function calculate()
    {
        //print_r($_POST);
        $qty_purchased = $this->input->post('qty_purchased');
        $item_cost = $this->input->post('item_cost');
        $mid_cal = $item_cost / $qty_purchased;
        $qty_used = $this->input->post('qty_used');
        $total_cost = $mid_cal * $qty_used ; 
        $this->load->view('Calculator',$total_cost,$mid_cal); 

        //$this->load->view('calculator');
    }


}

Below is my view

<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<body>

<form action="<?php echo base_url(); ?>index.php/calculator/calculate" method='post'>
  Item:<br>
  <input type="text" name="item" >
  <br>
  Qty Purchased:<br>
  <input type="text" name="qty_purchased" >
  <br>
  Cost of Item:<br>
  <input type="text" name="item_cost" >
  <br>
  Mid Cal:<br>
  <input type="text" name="mid_cal" value="<?php echo $mid_cal ?>">
  <br>
  Qty Used:<br>
  <input type="text" name="qty_used" >
  <br>
  Total Cost:<br>
  <input type="text" name="total_cost" value="<?php echo $total_cost ?>">
  <br><br>
  <input type="submit" value="Submit">
</form> 



</body>
</html>

I am getting undefined variable error in view for $total_cost and $mid_cal. I am sending the data in the calculate function. I also tried sending blank data in my index function. I am not sure how to solve this issue. Any help will be most welcome. Thanks in advance.

1 Answer 1

0

In your controller.

Replace Index Method/Function with below and try.

public function index()
{
    $data['mid_cal'] = 0;
    $data['total_cost'] = 0;
    $this->load->view('calculator',$data);
    //print_r($total_cost);

}

You have to pass an array in controller to the view as like above and now you can access directly using $total_cost and $mid_cal.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. It solved my issue. Just one more thing how can I use the set value function in the view form. I want all my data to stay even when the page is loaded to calculate() function from index() function. How can I achieve that?
Solved that problem also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.