2

I have created custom module called mymodule.

In this URL localhost/mymodule/name, I have this field:

$form['name'] = array(
  '#title' => t('Enter name'),
  ...
  '#ajax' => array(
    'event' => 'blur',
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'my-wrapper',
    'method' => 'replace',
  ),
  ...
);

My ajax callback is successfully called:

function mymodule_ajax_callback($form, &$form_state) {
  ...
  return ...
}

However, inside 'mymodule_ajax_callback', I need to get the current URL of the page which is localhost/mymodule/name. Currently it returns system/ajax which is how Drupal works by nature.

How to get the current URL inside the ajax callback?

2
  • You can save the current url in session when your page is render and can use the same in 'mymodule_ajax_callback'. – Jayendra Kainthola Sep 27 '13 at 10:40
  • 6
    You can get it from $form['#action'] – Jack-PL Sep 27 '13 at 10:53
3

As said by @Jayendra Kainthola
You need to store current path value in a session

$_SESSION['current_path'] = current_path();

Then use it inside your callback function as follows :

function mymodule_ajax_callback($form, &$form_state) {

$current_path = $_SESSION['current_path']  ;//gives the current path

}
2
  • 2
    Note that this disables page caching. – Lester Peabody Jun 8 '15 at 13:43
  • Perfect, just what I needed. – user1015214 Dec 29 '16 at 18:52
1

$form['#action'] can be used in order to meet the requirement of the Url. And then used as one want.

$form['#action']

Like:

function xyz_ajax_function($form, &$form_state){
  if(strpos($form['#action'], YOUR_URL_WANT_TO_CHECK)){
    echo 'yes';
  }else{
    echo 'no';
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.