Loïc N.
Loïc N.

Reputation: 393

Codeigniter : route doesn't work when calling php script through AJAX

I have a JS file which calls a php script using a relative path. The path used has a matching route in route.php.

The issue is that the route doesn't seem to be correctly applied when the php script is called from the JS file. More precisely, in the php file, the parameters $1 and $2 of the function do not contain the expected values (example below).

However, when using the url directly in the browser, the parameter $1 has the correct value.

route.php

$route['ajax/quizz/(:any)'] = 'test/ajax/$1';

JS file

var path        = 'ajax/quizz/load_items';  //path used for the AJAX query

Test.php

public function ajax($elt,$elt2 = "arg2"){

    switch($elt){
        case 'quizz' :
            echo "Shouldn't come here. Argument should be 'load_items': $1 $2";
            //$this->ajax_quizz();
            break;

        case 'load_items'   :
            $this->load_items($this->input->post(null,true));
            break;

        case 'add_stats'    :
            $this->add_stats($this->input->post(null,true),$_SESSION['id']);
            break;

        default :
            echo 'Unknown ajax function '.$elt;
    }
}

Expected behaviour

When the AJAX query is performed, the path specified (ajax/quizz/load_items) should match the route ajax/quizz/(:any) and the resulting path should be test/ajax/load_items.

As a consequence, we expect the controller test to be called, and function ajax to be executed, with argument $1 = load_items.

Actual behaviour

When called through AJAX, from the JS file, the path ajax/quizz/load_items has the following effect :

Direct access through the browser

When using this same path (http://localhost/codeigniter/ajax/quizz/load_items) directly in the browser, i get the expected behaviour :

Do you see where my issue might come from?

Upvotes: 1

Views: 1287

Answers (1)

Shaiful Islam
Shaiful Islam

Reputation: 7134

set your js ajax path full.Instead of using ajax/quizz/load_items use

http://localhost/codeigniter/ajax/quizz/load_items.

Upvotes: 2

Related Questions