Reputation: 569
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"); !
Upvotes: 0
Views: 1805
Reputation: 10300
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!'));
}
Upvotes: 0
Reputation: 108
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.
Upvotes: 0
Reputation: 31621
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));
}
Upvotes: 3