admin管理员组

文章数量:1384445

I'm trying to run wp_insert_attachment and update_user_meta using AJAX request but it doesn't work.

js file

import $ from "jquery";

class PersonalInfoUpdate {
  constructor() {
    this.events();
  }

  events() {
    document
      .getElementById("personalInfoUpdateForm")
      .addEventListener("submit", (e) => {
        const updPerBtn = document.getElementById("updPerBtn");

        updPerBtn.innerHTML = `<div class="spinner-border text-light" role="status">
        <span class="sr-only">Updating...</span>
      </div>`;

        function getGender() {
          if (document.getElementById("male").checked == true) {
            return "male";
          } else {
            return "female";
          }
        }

        $.ajax({
          url: studymoreData.ajax_url,
          type: "POST",
          dataType: "json",
          data: {
            action: "updateuserinfo",
            profilepicture: document
              .getElementById("imagePreview")
              .getAttribute("src"),
            sex: getGender(),
            dob: document.getElementById("dob").value,
            about: document.getElementById("about").value,
            security: studymoreData.user_update_nonce,
          },
          success: (response) => {
            if (response.updated == true) {
              console.log(response);
            } else {
              console.log(response);
            }
          },
          error: (response) => {
            console.log("Something went wrong");
            console.log(response);
          },
        });
        e.preventDefault();
      });
  }
}

export default PersonalInfoUpdate;

functions.php

function update_user_info()
{
  // First check the nonce, if it fails the function will break
  check_ajax_referer('user-update-nonce', 'security');

  // WordPress environment
  require( dirname(__FILE__) . '/../../../wp-load.php' );

  $wordpress_upload_dir = wp_upload_dir();
  // $wordpress_upload_dir['path'] is the full server path to wp-content/uploads/2017/05, for multisite works good as well
  // $wordpress_upload_dir['url'] the absolute URL to the same folder, actually we do not need it, just to show the link to file
  $i = 1; // number of tries when the file with the same name is already exists

  $profilepicture = $_FILES['profilepicture'];
  $new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
  $new_file_mime = mime_content_type( $profilepicture['tmp_name'] );

  while( file_exists( $new_file_path ) ) {
    $i++;
    $new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
  }

  // looks like everything is OK
  if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
    echo json_encode(array('updated'=>false, 'msg'=>'Uploadable', 'new_file_path'=>$new_file_path, 'profilepicture'=>$profilepicture, 'new_file_mime'=>$new_file_mime));

    $upload_id = wp_insert_attachment( array(
      'guid'           => $new_file_path, 
      'post_mime_type' => $new_file_mime,
      'post_title'     => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
      'post_content'   => '',
      'post_status'    => 'inherit'
    ), $new_file_path );

    // wp_generate_attachment_metadata() won't work if you do not include this file
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Generate and save the attachment metas into the database
    wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
  }

  $currentUserId = get_current_user_id();

  $update_desc_status = update_user_meta($currentUserId, 'description', esc_attr($_POST['about']));
  if (!$update_desc_status) {
    echo json_encode(array('updated'=>false, 'message'=>__('Description could not be updated. update_desc_status: ' .$update_desc_status)));
  }

  $update_dob_status = update_user_meta($currentUserId, 'date_of_birth', esc_attr($_POST['dob']));
  if (!$update_dob_status) {
    echo json_encode(array('updated'=>false, 'message'=>__('Date of Birth could not be updated. update_dob_status: ' .$update_dob_status)));
  }

  $update_sex_status = update_user_meta($currentUserId, 'sex', esc_attr($_POST['sex']));
  if (!$update_sex_status) {
    echo json_encode(array('updated'=>false, 'message'=>__('Sex could not be updated. update_sex_status: ' .$update_sex_status)));
  }

  die();
}

function please_login() {
  echo json_encode(array('updated'=>false, 'message'=>__('You are not logged in')));
  die();
}

add_action('wp_ajax_updateuserinfo', 'update_user_info');
add_action('wp_ajax_nopriv_updateuserinfo', 'please_login');

I'm not very well familiar with the modern REST API endpoints, so I used this method. I get as return the error portion in the AJAX request ('Something went wrong').

Can anybody help? Thanks in advance

本文标签: functionsWP AJAX Request Not Working