PHP未与Ajax POST一起运行

时间:2018-10-26 04:28:18

标签: javascript php jquery wordpress

我有一个模态形式的表格:

<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>

提交后,我运行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(); 
    });
});

然后它应该在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)));
    }
?>

但是在提交之后,什么也没有发生,并且数据没有保存在数据库中,这意味着无法正常工作。如果我在没有ajax的标准php中使用此php tho,它将起作用并将数据保存在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 个答案:

答案 0 :(得分:0)

浏览器控制台中存在错误:

$(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(); 
    });
});

注意

          else {
            $('.modal-body').html("Error!"); 
          }

错误:

  

未捕获到的SyntaxError:其他意外令牌

删除else块,它应该可以工作

应该是:

$(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!");
          }
      });
      event.preventDefault(); 
    });
});

这里是fiddle

答案 1 :(得分:0)

您尝试过吗?

 $( "#saveperson" ).submit(function( event ) {
       let form = $( this );

      let formData = new FormData(form[0]);

     $.ajax({ //Process the form using $.ajax()
        type      : 'POST', //Method type
        url       : 'process.php', 
        data      : formData, 
        success   : function(data) {
            $('.modal-body').html("Done!");
          }
      });
      event.preventDefault();

  });

答案 2 :(得分:0)

问题是我正在从外部php文件运行wordpress标准功能,但无法正常工作。为了实现我正在做的事情,我不得不使用

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';
    }
  }