Search code examples
phpjqueryajaxcodeigniterrestful-url

AJAX Returning PHP and head.php (page source)


I have some ajax here:

$.ajax({
    type: "POST",
    url: "<?=site_url('front_office/get_email_list/')?>",
    dataType: "text",
    success: function(response) {
        console.log(response)
    }
});

For some reason, this code returns the desired PHP but it also returns my head.php file.

function get_email_list() {
    $center_ids = array(
        /* list of user ids */
    );
    print_r(json_encode($this->user_model->get_email_list($center_ids)));
     /* get_email_list($center_ids)) returns a database query result */
}

And finally, my head.php contains your usual <head> tags with javascript and css imports.

Output looks something like:

**** return from php *****<head>header stuff</head>

I'd rather not parse out the header information but instead just get the PHP output.

Note: I am using codeiginiter and I am calling a function within the front_office controller.

Second note: I know I am not posting anything at the moment, but I will be soon. I tried GET but the problem persists.


Solution

  • You are returning the view, check request, if it is not ajax, load view, otherwise return json encoded result to your ajax request.

    if (!$this->input->is_ajax_request()) {
       // load view      
    }else{
        // Adding header, so jQuery ajax request will know that it is json
        // and result will be parsed immediately
       $this->output->set_content_type('application/json');
       $this->output->set_output(json_encode($email_list_result));
    }
    

    More about returning JSON at: Returning JSON from a PHP Script

    Also, check if you are loading head.php in constructor method ? Please, post whole code from controller.