1

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 :

  • The controller test is called
  • The function ajax is executed
  • Argument $1 = quizz (expected : load_items)
  • Argument $2 = load_items

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 :

  • The controller test is called
  • The function ajax is executed
  • Argument $1 = load_items

Do you see where my issue might come from?

Loïc N.
  • 353
  • 3
  • 17

1 Answers1

2

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

http://localhost/codeigniter/ajax/quizz/load_items.
Shaiful Islam
  • 7,034
  • 12
  • 38
  • 58
  • Hello Shaiful. First, thank you for your answer. It does work when i put the full URL, as you suggested. However, it is very important for me to keep a relative path, as later, it will not be "localhost/codeigniter/ajax/quizz/load_items, but something like www.my-website/ajax/quizz/load_items. So i really need to keep a relative path. – Loïc N. Mar 16 '15 at 18:56
  • You can look here http://stackoverflow.com/questions/27420759/codeigniter-base-url-not-working-properly-for-ajax how you can make initial parts dynamically – Shaiful Islam Mar 16 '15 at 19:35
  • Hello Shaiful. Thanks a lot. Link you provided corrected my issue. – Loïc N. Mar 21 '15 at 15:25