CodeIgniter - How to return Json response from controller

后端 未结 4 1215
梦谈多话
梦谈多话 2020-12-05 10:15

How do I return response from the controller back to the Jquery Javascript?

Javascript

$(\'.signinform\').submit(function() { 
   $(this).ajaxSubmit(         


        
相关标签:
4条回答
  • 2020-12-05 10:28
    return $this->output
                ->set_content_type('application/json')
                ->set_status_header(500)
                ->set_output(json_encode(array(
                        'text' => 'Error 500',
                        'type' => 'danger'
                )));
    
    0 讨论(0)
  • 2020-12-05 10:31

    This is not your answer and this is an alternate way to process the form submission

    $('.signinform').click(function(e) { 
          e.preventDefault();
          $.ajax({
          type: "POST",
          url: 'index.php/user/signin', // target element(s) to be updated with server response 
          dataType:'json',
          success : function(response){ console.log(response); alert(response)}
         });
    }); 
    
    0 讨论(0)
  • 2020-12-05 10:52

    For CodeIgniter 4, you can use the built-in API Response Trait

    Here's sample code for reference:

    <?php namespace App\Controllers;
    
    use CodeIgniter\API\ResponseTrait;
    
    class Home extends BaseController
    {
        use ResponseTrait;
    
        public function index()
        {
            $data = [
                'data' => 'value1',
                'data2' => 'value2',
            ];
    
            return $this->respond($data);
        }
    }
    
    0 讨论(0)
  • 2020-12-05 10:53
    //do the edit in your javascript
    
    $('.signinform').submit(function() { 
       $(this).ajaxSubmit({ 
           type : "POST",
           //set the data type
           dataType:'json',
           url: 'index.php/user/signin', // target element(s) to be updated with server response 
           cache : false,
           //check this in Firefox browser
           success : function(response){ console.log(response); alert(response)},
           error: onFailRegistered
       });        
       return false; 
    }); 
    
    
    //controller function
    
    public function signin() {
        $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    
    
       //add the header here
        header('Content-Type: application/json');
        echo json_encode( $arr );
    }
    
    0 讨论(0)
提交回复
热议问题