简体   繁体   中英

Pass a value from Controller to jQuery CodeIgniter

This is Insert_model

class Insert_model extends CI_Model{
   public function idp(){
   $sql = sprintf("SELECT npd from `dosen`  ORDER BY npd DESC LIMIT 1");
   $query = $this->db->query($sql);
   foreach ($query->result_array() as $key ) {
       $npd1 = $key['npd'];
   }
   $kalimat1 = substr($npd1, 0,3);
   return $kalimat1;
}

This is a function from the Register Controller:

class Register extends CI_Controller{
  public $model;
  public function __construct(){
      parent::__construct();
      $this->load->helper(['url','html']);
      $this->load->database();
      $this->load->model('Insert_model');
      $this->model=$this->Insert_model;
  }
  public function index(){
      $nomor= array('npd' => $this->model->idp());
      echo json_encode($nomor);
  }
}

This is how I access the $nomor value via Ajax:

$("#status").on("change", function(){
var x = $("#status option:selected").attr("value");
if(x=='mahasiswa'){
    $.ajax({
        url:'<?php echo base_url();?>register/index',
        type: 'POST',
        dataType: 'json',
        success : function(nomor){
            $('#nomor').attr('placeholder',nomor.npd);
        },
    });
});

I want to be able to pass $nomor from the Register Controller to use it on my jQuery file. I tried to use json_encode() on the Controller and actually it didn't work.

Try with controller: Ref : https://www.codeigniter.com/userguide3/general/models.html

$this->load->model('model_name');
$data['npd'] = $this->model_name->method();
echo json_encode($data);

Try This,

public function index(){
      $nomor= array('npd' => $this->model->idp());
      echo json_encode($nomor);
      exit();
  }

i hope this will help you

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