-1

ボタンクリック時にテキストボックスからデータを保存したい。以下のように、このタスクに JQuery AJAX を使用しています。このタグはテーマ関数内に作成したことに注意してください。

function theme_user_post_block($vars)
{

$themeUserCommentInput ='';

$themeUserCommentInput .= '<textarea id="txt_1"rows="1" cols="50"></textarea>';

$themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center"
class="btnPostComment" id="btn_1" />'
return $themeUserCommentInput;
}

これにより、ページ内にテキストボックスとボタンを表示できます。ここに私のJSコードがあります:-

(function($) 
{   
Drupal.behaviors.PostComment= { 

 attach: function (context, settings) {
  $('.btnPostComment', context).click(function (event) {
  var post = "&newcomment=Comment1&logid=log1";
  jQuery.ajax({
              url: 'postcomment',
              type: 'POST',
              dataType: 'json',
              data: post,
              success: function (data) { alert(data); },
              error: function(jqXHR, textStatus, errorThrown){alert(textStatus + 
   errorThrown);}
      });               
     });
    }                    
   }
  })(jQuery); 

次に、次のように URL 名でメニュー ページを作成します。

 function postcomment_menu(){
 $items=array();
  $items['postcomment']=array(
   'title'=>t(''),
   'type'=> MENU_CALLBACK,       
   'page callback' => 'user_comment_post',        
   'access arguments' => array('access content'),
 );
 return $items; 
}

function user_comment_post(){
 global $user;
 $cid =  db_insert('user_comment')
    ->fields(array(     
    'comment_user_id' => $user->uid,
    'reference_id' => $_POST['logid'],      
    'comment_desc'=>$_POST['newcomment'],
    'createdon'=>REQUEST_TIME, 
    ))
    ->execute();
  if($cid!=0)
  {
     //GetUserComments($i);
     drupal_json_output("success");
  }
}

したがって、jQuery + Ajax Submit 機能に必要なすべてのことを行いました。「コメントを投稿」ボタンを押すと、アラートに「errorundefined」というエラーが表示されます。アラートは、jQuery.AJAX 関数内のエラーの結果として表示されます。また、カスタム メニューのコールバックも呼び出されません。

4

2 に答える 2