dqqs64238 2018-10-26 04:28
浏览 84
已采纳

PHP没有使用ajax POST运行

I have a form in a modal:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Add user
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form action="" method="post" id="saveperson">
            <label for="newcat">Project Name</label>
            <input type="text" name="newcat" value="">
            <label for="description">Description</label>
            <input type="text" name="description" value="">
            <input type="submit" name="user" value="Submit">
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

On submit I run the js:

$(document).ready(function() {
    $('#saveperson').submit(function(event) { //Trigger on form submit
      var postForm = { //Fetch form data
        'name'     : $('input[name=newcat]').val(),
        'desc'     : $('input[name=description]').val() //Store name fields value
      };
      $.ajax({ //Process the form using $.ajax()
        type      : 'POST', //Method type
        url       : 'process.php', 
        data      : postForm, //Forms name
        dataType  : 'json',
        success   : function(data) {
            $('.modal-body').html("Done!");
          }
          else {
            $('.modal-body').html("Error!"); 
          }
        }
      });
      event.preventDefault(); 
    });
});

And then this should run in process.php

<?php 
    header ( "Content-Type: application/json");
    $cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );  
    // Check if category exists
    if($cat_ID == 0) {
        $cat_name = sanitize_text_field($_POST['newcat']);  
        $cat_desc = sanitize_text_field($_POST['description']);
        $cat_slug = sanitize_title_with_dashes($cat_name);
        $my_cat = array(
            'cat_name' => $cat_name, 
            'category_description' => $cat_desc, 
            'category_nicename' => $cat_slug, 
            'category_parent' => 0
        );
        if( wp_insert_category( $my_cat ) ) {
            // Category added successfully
            die ( json_encode ( array ( "success" => 1)));
        } else {
            // Error while creating new category
            die ( json_encode ( array ( "success" => 0)));
        }
    } else {
        // That category already exists
        die ( json_encode ( array ( "success" => 0)));
    }
?>

But after the submit, nothing happens and the data isn't saved in the db, meaning isn't working. If I use this php tho in a standard php without ajax, it works and saves the data in the db

<?php 
    header ( "Content-Type: application/json");
    if( isset( $_POST['user'] ) ) {
        if( !empty( $_REQUEST['newcat'] ) ) {
            $cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );  
            // Check if category exists
            if($cat_ID == 0) {
                $cat_name = sanitize_text_field($_POST['newcat']);  
                $cat_desc = sanitize_text_field($_POST['description']);
                $cat_slug = sanitize_title_with_dashes($cat_name);
                $my_cat = array(
                    'cat_name' => $cat_name, 
                    'category_description' => $cat_desc, 
                    'category_nicename' => $cat_slug, 
                    'category_parent' => 0
                );
                wp_insert_category( $my_cat );
            }
        }
    }
?>
  • 写回答

3条回答 默认 最新

  • douweihui0178 2018-10-26 05:34
    关注

    The issue was I was running wordpress standard functions from an external php file and it doesn't work. In order to achieve what i was doing, I had to use

    function.php and wordpress ajax
    
      add_action( 'wp_footer', 'ajax_Person' );
    
      function ajax_Person() { ?>
        <script type="text/javascript">
        jQuery("#createCat").on("click", function(e){
          e.preventDefault();
          person();
        });
        function person(){
          jQuery.ajax({
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            type: 'post',
            data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
            success: function(data) {
    
            }
          });
        }
        </script>
      <?php }
    
      add_action('wp_ajax_data_person' , 'data_person');
      add_action('wp_ajax_nopriv_data_person','data_person');
    
      function data_person(){
        $catname = $_POST['catName'];
        $catdesc = $_POST["catDesc"];
        $cat_ID = get_cat_ID( sanitize_title_for_query($catname) );  
        // Check if category exists
        if($cat_ID == 0) {
            $cat_name = $catname;  
            $cat_desc = $catdesc;
            $cat_slug = sanitize_title_with_dashes($cat_name);
            $my_cat = array(
              'cat_name' => $cat_name, 
              'category_description' => $cat_desc, 
              'category_nicename' => $cat_slug, 
              'category_parent' => 0
            );
            if( wp_insert_category( $my_cat ) ) {
              echo 'Category added successfully';
            } else {
              echo 'Error while creating new category';
            }
        } else {
          echo 'That category already exists';
        }
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基与机器学习和时间序列分析预测养老服务需求趋势
  • ¥100 求连续两帧图像在水平和垂直上偏移
  • ¥15 mysql全文索引查找指定必须关键词word无效
  • ¥15 Verilog hdl密码锁设计
  • ¥35 基于python的有ssl加密传输的socket聊天室
  • ¥15 数码管亮度控制器设计
  • ¥15 kafka客户端跨网段访问,看日志提示连接的还剩内网地址,且访问不通
  • ¥15 关于c语言代码的问题
  • ¥15 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备