Drupal - Post Data via Ajax to PHP Menu Callback with JQuery and JSON
Category:
Drupal 7
I found this solid example for Drupal 7.
http://www.computerminds.co.uk/drupal-code/make-link-use-ajax-drupal-7-its-easy
The code for D7 is much more elegant, there are some great new features in D7 to make this stuff easier.
Drupal 6
Put this PHP code inside your module, e.g. sites/all/modules/my_module/my_module.module
drupal_add_js(drupal_get_path("module","my_module") . "/my_module.js"); function my_module_perm () { return array( 'access my_module via ajax', ); } function my_module_menu () { $items = array(); $items['my_module/example'] = array( 'page callback' => 'my_module_example', 'access arguments' => array('access my_module via ajax'), 'type' => MENU_CALLBACK, ); return $items; } function my_module_example () { if (empty($_POST["js"])){ die(); } $result = array('msg' => 'my_module_example - hello from php','valid' => true); drupal_json($result); exit(); }
Put this Javascript code inside your module's javascript file, e.g. sites/all/modules/my_module/my_module.js
if (Drupal.jsEnabled) { $(document).ready(function () { // ajax return var my_module_example = function (data) { alert(data.msg); } // ajax call $.ajax({ type: 'POST', url: Drupal.settings.basePath + 'my_module/example', dataType: 'json', success: my_module_example, data: 'js=1&my_module_post_data=2012' }); }); }
Don't forget to clear Drupal's menu cache and grant permissions to your users to be able to access the menu callback url.
Comments
antonio talamo (not verified)
Sat, 10/12/2013 - 23:12
Permalink
hi..i'm new developer in
hi..i'm new developer in drupal...sorry for my question..
I have my function
i want use my tweets in client side..to get them with ajax in javascript I'll have to 'do the following or wrong?
thanks..
tyler
Mon, 10/14/2013 - 09:56
Permalink
This looks like it would work
This looks like it would work well. I'm not too familiar with the .getJSON function, but I'm sure it works well. I'd recommend not using the drupal_add_js call to add your script. Instead use your module.info file to make Drupal aware of your javascript file.
https://drupal.org/node/304255
antonio talamo (not verified)
Mon, 10/21/2013 - 11:05
Permalink
I already inserted the
I already inserted the script in mymodule.info but it would seem that the url does not work in $.getJSON OR AJAX