简体   繁体   中英

CodIgniter: why I get html response instead of json response when sending ajax request

I send and ajax request to the server and I want to receive json response but instead, I receive html response, what is the wrong in this code?

//jquery code

$('select[name=category]').click(function(){
    $.ajax({
    url: "/index.php/category/get_categories",
    type: "post",  
    dataType: "json",
    cache: false,      
    success: function (result) { 
        var arr = jquery.parseJSON(result);
        alert(arr);
        }      
    });
});

//php code

public function get_categories(){
    $data = $this->category_model->get_cats_names_ids();
    echo json_encode($data);
}

the response is an html page instead of json object and the alert box dose not appear. when I remove dataType:"json", the alert box appear and contain html page ! and any code after "var arr = jquery.parseJSON(result);" does not work, ex. alert("hi"); !

I don't know if this will completely resolve your problem (there may be a display hook or other view machinery involved which is generating html), but start here.

Rule 1: Never echo anything from your controller. Either invoke a view or use output::set_output .

Rule 2: Always set your content-type correctly.

public function get_categories(){
    $data = $this->category_model->get_cats_names_ids();
    $this->output->set_header('Content-type:application/json');
    $this->output->set_output(json_encode($data));
}

It seems that there is something error in your model and the HTML response you got is CI error message.

Just for debugging, echo the $data without json_encode and then call that function directly via URL.

try following

$('select[name=category]').click(function()
{
 $.post( '<?php echo site_url('category/get_categories'); ?>', { 'var': 1 },
       function(response) {
       if(response.success)
    {
         var arr = response.message;
                     alert(arr);
    }       
      },"json");


});

 public function get_categories()
 {
    $data = $this->category_model->get_cats_names_ids();
    echo json_encode(array('success'=>true,'message'=>$data));
    //for testing replace above line with
    // echo json_encode(array('success'=>true,'message'=>'Hello!'));
 }

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