简体   繁体   中英

Returning data from controller - Codeigniter

I am trying to return data to my variable $item_id but the variable returns empty. Am i not returning the data the right way??

item_id should return "Alert" which is coming from the index function in serverMonitor.php.

Please advice. Thank you

Items.php

 function rest_state()
  {
     $id = 1;
     $item_id =  $this->pass_to_res($id);
     return $item_id //this should return "Alert"

  }



function pass_to_res($id)
   {
      $url = "https://example.com/serverMonitor?id=$id";
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
      $result = curl_exec($ch);
      curl_close ($ch);
      return $result;
   }

serverMonitor.php

 function index() {

        $id = htmlentities($_GET['id']);
        $word = "Alert";
        return $word;
    }

Return values from a function are not always visible to the visitor. You should use echo, print or print_r.

 function index() {
        $id = htmlentities($_GET['id']);
        $word = "Alert";
        echo $word;
        return true;
    }

You can also use JSON with json_encode to encoding

function index() {
            $id = htmlentities($_GET['id']);
            $word = "Alert";
            echo json_encode(['word' => $word]);
            return true;
        }

And json_decode to decoding:

function pass_to_res($id)
   {
      $url = "https://example.com/serverMonitor?id=$id";
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
      $result = curl_exec($ch);
      curl_close ($ch);

      $result = json_decode($result);
      return isset($result['word']) ? $result['word'] : false;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM