/**
* Implements hook_init().
*/
function YOUR_MODULE_NAME_init()
{
drupal_add_js('misc/jquery.form.js');
drupal_add_library('system','drupal.ajax');
}
<a href="text/ajax/nojs/1234" class="use-ajax">ajaxリンク</a>
/**
* Implements hook_init().
*/
function test_module_init()
{
drupal_add_js('misc/jquery.form.js');
drupal_add_library('system','drupal.ajax');
}
/**
* Implementation of hook_menu()
*/
function test_module_menu() {
$items['test/ajax/%/%']=array( // URLの2,3番目がクライアント側で生成
'page callback' => 'ajax_node_response',
'page arguments' => array(2,3), // URLの2,3番目の引数をコールバック関数に渡す
'access callback' => 'user_access',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function ajax_node_response($type="ajax", $nid=0){
$node = node_load( $nid, NULL, false );
$vnode = node_view($node);
$output = theme('node', $vnode);
if( $type="ajax" ){
$commands=array();
$commands[]=ajax_command_replace( '#block-system-main','<section id="block-system-main">'.$output.'</section>' ) ;
$page = array(
'#type' => 'ajax',
'#commands' => $commands,
);
ajax_deliver( $page ) ; // ajax対応ブラウザの結果
} else {
$output = '<div id="content">'.$output.'</div>'; // ajax非対応ブラウザの結果
return $output;
}
}
drupal_add_js("/misc/ajax.js") ; // ajaxのjsファイルをインポート
// 例: DrupalのAPIでフォームを作成
// 送信ボタンを押して、"test message"の文字列でフォームを置換します
$form['card_last']=array(
"#type" => "markup",
"#markup" => "",
"#prefix" => "<div id='card-last-result-div'>", // ajaxで置換したいエリア
"#suffix" => "</div>",
);
$form['card_last']['submit'] = array(
'#type' => 'submit',
'#value' => '送信',
'#attributes' => array( 'id'=>'test-form-submit' ), // ajaxのIDを指定します
"#ajax" => array(
"callback" => "_ajax_callback_form", // ajaxのコールバック
'wrapper' => 'card-last-result-div',
'method' => 'replace',
'effect' => 'fade',
),
);
// カスタムJSファイルをフォームと一緒に添付
$form['#attached']['js'] = array( "file_path/custom_ajax.js" );
(function($){
Drupal.behaviors.custom_module_name={
attach:function(cotext,settings){
$("#test-form-submit").once("test-form-submit",function(){ //指定したフォームのみ
var base = $(this).attr('id'); //フォームIDの使用
var element_settings = {
url: window.location.protocol + "//"+ window.location.hostname + settings.basePath + settings.pathPrefix + "system/ajax",
event: 'click',
progress: { type: 'throbber', },
};
// Drupalのajaxオブジェクトを生成します
Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
// 送信ボタンにListenerを追加
$("#test-form-submit").on( 'click',function(){
$(this).click(); // ajaxを作動させます
});
});
}
};
})(jQuery)
function _ajax_callback_card_last_form($form, &$form_state){
$commands[] = ajax_command_replace('#card-last-result-div', "test message");
return array('#type' => 'ajax', '#commands' => $commands);
}