Last active
December 20, 2015 14:28
-
-
Save crazyrohila/6146380 to your computer and use it in GitHub Desktop.
Ajax Request in drupal Module by javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
We have to change a field value when changing other field. Drupal Ajax menu is right method, but I found other way easier. | |
hook_menu :- Create a url with hook_menu. | |
page_callback :- In page callback we have to process all things and return data (in json format) that will need in javascript. | |
drupal_add_js :- Now use $.get method in js and hit that url and parse json ($.parseJSON) data from response and perform other actions. | |
/*======== Code Example==========*/ | |
/** | |
* Implements hook_menu(). | |
*/ | |
function test_menu() { | |
return array( | |
'test' => array( | |
'title' => 'Test', | |
'page callback' => 'test_page', | |
'type' => MENU_CALLBACK, | |
'access callback' => TRUE, | |
), | |
); | |
} | |
/** | |
* callback function. | |
*/ | |
function test_page() { | |
$data = array('greeting' => 'hello', 'name' => 'json'); | |
$json_data = json_encode($data); | |
print_r($json_data); die(); | |
} | |
If you want to receive only data required, nothing else in javascript-end then use die(); otherwise return $json_data; | |
drupal_add_js(' | |
$("#selectfield").change(function() { | |
$.get(Drupal.settings.basePath+"test/", function(response) { | |
var resp = $.parseJSON(response); | |
console.log(resp); | |
$("textfield").val(resp.greeting+" "+resp.name).change(); | |
}); | |
});', 'inline'); | |
That's it. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment