如何在wordpress插件中使用ajax提交表单

时间:2014-02-27 11:48:51

标签: ajax wordpress plugins

我正在创建一个小插件,我想使用ajax提交表单数据,但它的响应为零。

这是我的电话,我暂时将所有代码添加到单个文件中

文件名:index.php

<?php wp_enqueue_script("jquery");?>
  <?php

   function myaddgallery(){
   global $wpdb;    
   echo "abac";

   }

   add_action('wp_ajax_myaddgallery' , 'myaddgallery');
   add_action('wp_ajax_nopriv_myaddgallery' , 'myaddgallery');

   ?>
   <script type="text/javascript">
     jQuery(document).ready(function(){
     jQuery('#shaGalleryForm').submit(function(e){

         // prevent normal submit behaviour
    e.preventDefault();
     var name = jQuery("#shaGalleryName").val();
         alert(name);
          //var postData = jQuery("#shaGalleryForm").serialize();
          //console.log(postData);
          var name = "shalu";
          jQuery.ajax({
              type: "POST",
              url: "http://localhost/plugindevelop/wp-admin/admin-ajax.php",
              data : {action: "myaddgallery", name : name},
              success: function(response){
                  //console.log(postData);
                  console.log("added success");
                  alert(response);
              },
              error: function(data){
                  console.log("fail");
              }
          });
     });
 }) ; 


</script>


<div class='wrap'>
    <h2>Add Gallery</h2>
    <p>This is where from you can create new gallery</p>
    <form name="shaGalleryForm" id="shaGalleryForm" method="post">
        <table class="form-table">
            <tr>
                <th>Gallery Name</th>
                <td>
                    <input type="text" id="shaGalleryName" name="shaGalleryName">
                    <p class="description">Add gallery name also please avoid special character</p>
                </td>

            </tr>


        </table>
        <p class="submit">
            <input type="submit" value="Save" id="shaSaveGallery" name="shaSaveGallery" class="button button-primary">
        </p>
    </form>
</div>

1 个答案:

答案 0 :(得分:0)

尝试在回显数据后添加die()

function myaddgallery(){
 global $wpdb;    
 echo "abac";
 die();
}