user1877722
user1877722

Reputation: 31

CodeIgniter gives me error 404 but I can see response in Firebug

I have already read some questions very similar in SO, but none of the solutions worked for me.

The problem is, for example, with this code in the view:

$.ajax({
url: 'periodista/json',
async: false,
dataType: 'json',
success: function (json) {
$.each(json, function(k,v){valores.push(v); });

}

I get a 404 Not Found error, but Firebug shows me the Response (http://i.imgur.com/yG9cW.png)

I've tried to read the url response from a simple php script with file_get_contents function but it doesn't work

$url="http://localhost/xampp/populus/wordpress/app/periodista/json";
$json = file_get_contents($url);

I get the same answer (404 error, and I can read the response in Firebug).

I've tried using the "index.php" URLs, the URLs without index.php with help of an htaccess, and using the complete URLs but nothing worked. And I'm not using wordpress.

I think the controller is not loaded when I try to access the view, but I don't know why.

Edit: My Controller function code (I'm using Ignited Datatables library):

    public function json()
{
    $datatables = new Datatables();
    $datatables->select('nro_boletin')->from('proyecto_de_ley');
    echo $datatables->generate();


    $data['title'] = "Periodista";
    $this->load->view('periodista/json', $data);

}

Upvotes: 2

Views: 1143

Answers (2)

NFT Master
NFT Master

Reputation: 1490

I had a similar issue and I had to set header manually.

public function get_prev_input_data()
{
    header("HTTP/1.1 200 OK");
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");

    $userdata = [
        "id" => 5,
        "username" => "captain hook",
    ];

    $prev = [
        "a1" => 123,
        "a2" => 46,
    ];
    $response = [
        "userdata" => $userdata,
        "previnput" => $prev
    ];
    echo json_encode($response);
}

So you should add this line

    header("HTTP/1.1 200 OK");

in your json() function.

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

try setting content type json and outputting it instead of loading view, like:

public function json() {
    $datatables = new Datatables();
    $datatables->select('nro_boletin')->from('proyecto_de_ley');
    echo $datatables->generate();


    $data['title'] = "Periodista";
    $this->output
               ->set_content_type('application/json')
               ->set_output(json_encode($data));
   //OR
   header('Content-Type: application/json',true);
   echo json_encode($data);

}

Since you are using ajax, your function is called

$.ajax({
    url: 'periodista/json', <-- your controllers function
    data: {"test" : "test" },
    async: false,
    dataType: 'json',
    success: function (json) { //output from your json function
          $.each(json, function(k,v){valores.push(v); });
    }

Upvotes: 0

Related Questions