如何修复Wordpress admin-ajax中的404错误?

时间:2018-11-29 16:57:29

标签: php jquery wordpress advanced-custom-fields

我正在尝试使用ajax自定义提交高级自定义字段专业数据,其中包括图像字段,而无需使用acf提供的本机提交。

似乎重新发明了轮子,但这是它适用于我的用例的唯一方法,该用例是一个多步骤表单。开箱即用acf不提供此功能。

我目前收到 POST https://dev.energypages.com/wp-admin/admin-ajax.php 400()错误,我不确定为什么,如果您能有新的眼光看我的代码并查看它们是否能为我所用,我将不胜感激可以找到我找不到的任何问题。

我也没有成功获得图像数据和字符串数据。

Javascript:

$(".nexttwo").on('click', function() {
  resetErrors();

  current_fs = $(this).parent();
  next_fs = $(this).parent().next();
  var comid = getUrlParameter('cid');

  var companydata = new FormData(this);
  companydata.append("comdata", "company_info");
  companydata.append("cid", comid);

  $.ajax({
    url: ajaxurl,
    processData: false,
    contentType: false,
    dataType: 'json',
    method: 'post',
    data: companydata,
    success: function(data) {
      console.log(JSON.stringify(data));
      for (var i = 0; i < data.length; i++) {
        var status = data[i].code;
        var field = data[i].field;
        var message = data[i].msg;
        //var comid = data[i].cid;

        if (status == "200") {
          //successful validation
          if (animating) return false;
          animating = true;

          //activate next step on progressbar using the index of next_fs
          $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

          //show the next fieldset
          next_fs.show();
          //hide the current fieldset with style
          current_fs.animate({
            opacity: 0
          }, {
            step: function(now, mx) {
              //as the opacity of current_fs reduces to 0 - stored in "now"
              //1. scale current_fs down to 80%
              scale = 1 - (1 - now) * 0.2;
              //2. bring next_fs from the right(50%)
              left = (now * 50) + "%";
              //3. increase opacity of next_fs to 1 as it moves in
              opacity = 1 - now;
              current_fs.css({
                'transform': 'scale(' + scale + ')'
              });
              next_fs.css({
                'left': left,
                'opacity': opacity
              });
            },
            duration: 800,
            complete: function() {
              current_fs.hide();
              animating = false;
            },
            //this comes from the custom easing plugin
            easing: 'easeInOutBack'
          });
        } else {
          var msg = '<label class="acf-notice -error acf-error-message error" for="' + field + '">' + message + '</label>';
          $('input[name="' + field + '"], select[name="' + field + '"]').addClass('acf-error').before(msg);
        }
      }
    }
  });
});

PHP:

function company_info($post_id){
    if( isset($_POST['cid']) )
    $post_id = $_POST['cid'];

    // These files need to be included as dependencies when on the front end.
    require_once( ABSPATH . 'wp-load.php');

    //Log form data
    $file_path = plugin_dir_path( __FILE__ );
    $filename = $file_path.'companyinfo.txt';

    //Get form data
    $data = $_POST['comdata'];

    file_put_contents($filename, $data);

    $formdata = array();
    parse_str($data, $formdata);


    //Prepare company info
    $cname = strtolower($formdata['acf']['field_5bef0f8c743f6']);
    $clogo = $formdata['acf']['field_5bef0fac743f7'];
    $cwebsite = $formdata['acf']['field_5bef100b743f8'];
    $cphone = $formdata['acf']['field_5bef1032743f9'];
    $caddress = $formdata['acf']['field_5bef108a743fa'];

    $errorMSG = [];

    /* COMPANY NAME */
    if ( empty($cname) ) {
        $errorMSG[] = array('code' => 404, 'field' => 'acf[field_5bef0f8c743f6]', 'msg' => 'Company name is required');
    }

    /* COMPANY LOGO */
    if ( empty($clogo) ) {
        $errorMSG[] = array('code' => 404, 'field' => 'acf[field_5bef0fac743f7]', 'msg' => 'Company logo is required');
    }

    $success = [];

    if( empty($errorMSG) ){
        $uploadedfile = $_FILES['acf[field_5bef0fac743f7]'];
        $upload_name = $_FILES['acf[field_5bef0fac743f7]']['name'];
        $uploads = wp_upload_dir();
        $filepath = $uploads['path']."/$upload_name";

        if ( ! function_exists( 'wp_handle_upload' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
        }
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        require_once( ABSPATH . 'wp-admin/includes/media.php' );

        $upload_overrides = array( 'test_form' => false );
        $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
        if ( $movefile && !isset( $movefile['error'] )  ) {

            $file = $movefile['file'];
            $url = $movefile['url'];
            $type = $movefile['type'];

            $attachment = array(
                'post_mime_type' => $type ,
                'post_title' => $upload_name,
                'post_content' => 'File '.$upload_name,
                'post_status' => 'inherit'
                );

            $attach_id = wp_insert_attachment( $attachment, $file, 0);
            $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
            wp_update_attachment_metadata( $attach_id, $attach_data );

        }
        // Let WordPress handle the upload.
        //$img_id = media_handle_upload( 'acf[field_5bef0fac743f7]', 0 );

        file_put_contents($filename, $attach_id);

        update_field('field_5bef0fac743f7', $attach_id, $post_id);


        update_field('field_5bef0f8c743f6', $cname, $post_id);
        update_field('field_5bef100b743f8', $cwebsite, $post_id);
        update_field('field_5bef1032743f9', $cphone, $post_id);
        update_field('field_5bef108a743fa', $caddress, $post_id);

        $success[] = array('code' => 200);
        echo json_encode($success);

        exit();
    }

    echo json_encode($errorMSG);

    exit();
}
add_action('wp_ajax_company_info', 'company_info');
add_action('wp_ajax_nopriv_company_info', 'company_info');
add_action('acf/save_post' , 'company_info', 20 );

图像字段HTML:

<div class="acf-field acf-field-image acf-field-5bef0fac743f7" style="width:50%;" data-name="company_logo" data-type="image" data-key="field_5bef0fac743f7" data-required="1" data-width="50">
  <div class="acf-label">
    <label for="acf-field_5bef0fac743f7">COMPANY LOGO <span class="acf-required">*</span></label>
  </div>

  <div class="acf-input">
    <div class="acf-image-uploader" data-preview_size="thumbnail" data-library="all" data-mime_types="" data-uploader="basic">
      <input name="acf[field_5bef0fac743f7]" value="url=C%3A%5Cfakepath%5C4change-energy-logo.png" type="hidden">

      <div class="show-if-value image-wrap" style="max-width: 150px">
        <img data-name="image" src="" alt="" class="pk-pin-it-ready">
        <div class="acf-actions -hover">
          <a class="acf-icon -cancel dark" data-name="remove" href="#" title="Remove"></a>
        </div>
      </div>

      <div class="hide-if-value">
        <label class="acf-basic-uploader">
                    <input name="acf[field_5bef0fac743f7]" id="acf-field_5bef0fac743f7" type="file">                           </label>

      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

删除processData:false,并手动检查“ ajaxurl”后面的URL。做这两件事必须避免得到404