jquery AJAX 问题未显示已评级的警告未显示

hiz5n14c  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(75)

我很累在wordpress上工作这个代码。从技术上讲,我计划建立一个电影分级系统。
所以我的计划是,当用户没有登录,然后弹出警告说:“请先登录后评级。”同样,当你已经评级的电影,然后弹出这个“你已经评级这部电影”。
功能评级工作正常。但是,警告弹出窗口未显示原因?请帮帮我。我没有任何错误在我的控制台。
这里是我的代码。
rating-script.js

jQuery(document).ready(function($) {
    // Function to handle rating submission
    function handleRatingSubmission(postID, ratingValue) {
      // Check if user is logged in
      if (ratingAjax.isLoggedIn === false) {
        // User is not logged in, show error message
        $('.rating-error-message').text('Please login first before rating.').fadeIn().delay(3000).fadeOut();
        return;
      }
  
      // Send AJAX request to check if user has already rated
      $.ajax({
        url: ratingAjax.ajaxurl,
        type: 'POST',
        data: {
          action: 'check_already_rated',
          post_id: postID
        },
        success: function(response) {
          if (response.alreadyRated) {
            // User has already rated, show error message
            $('.rating-error-message').text('You have already rated this movie.').fadeIn().delay(3000).fadeOut();
          } else {
            // User has not rated, proceed with rating submission
            // Send AJAX request to update rating
            $.ajax({
              url: ratingAjax.ajaxurl,
              type: 'POST',
              data: {
                action: 'update_rating',
                post_id: postID,
                rating_value: ratingValue * 2 // Multiply the rating by 2 to convert it back to the original scale of 1-10
              },
              success: function(response) {
                if (response.success) {
                  // Rating updated successfully
                  // Display success message
                  $('.rating-success-message').fadeIn().delay(3000).fadeOut();
  
                  // Update the rating display
                  updateRatingDisplay(postID, ratingValue);
  
                  // Update the average rating display
                  var averageRating = parseFloat(response.average_rating).toFixed(2);
                  $('.rating-info[data-post-id="' + postID + '"] .average-rating').text('Average Rating: ' + averageRating);
  
                  // Update the total ratings display
                  var totalRatings = response.total_ratings;
                  $('.rating-info[data-post-id="' + postID + '"] .total-ratings').text('Total Ratings: ' + totalRatings);
                } else {
                  // Error occurred during rating update
                  // You can add additional error handling logic here
                }
              },
              error: function() {
                // Error occurred during AJAX request
                // You can add additional error handling logic here
              }
            });
          }
        },
        error: function() {
          // Error occurred during AJAX request
          // You can add additional error handling logic here
        }
      });
    }
  
    // Function to update the rating display
    function updateRatingDisplay(postID, ratingValue) {
      // Add your code here to update the rating display
      // This function should update the visual representation of the rating based on the given rating value and post ID
      // You can modify the DOM elements to reflect the updated rating
    }
  
    // Handle hover effect on rating stars
    $('.rating-stars .star').hover(function() {
      var value = $(this).data('value');
      $(this).prevAll().addBack().addClass('hover');
      $(this).nextAll().removeClass('hover');
      $(this).parent().next('.rating-hover-text').text(value);
    }, function() {
      $(this).prevAll().addBack().removeClass('hover');
      $(this).parent().next('.rating-hover-text').text('');
    });
  
    // Handle rating submission
    $('.rating-stars .star').click(function() {
      var postID = $(this).data('post-id');
      var ratingValue = $(this).data('value');
  
      // Handle rating submission for logged-in users only
      handleRatingSubmission(postID, ratingValue);
    });
  });

字符串
functions.php

<?php
// Enqueue necessary scripts and styles
function enqueue_rating_scripts() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('rating-script', get_template_directory_uri() . '/js/rating-script.js', array('jquery'), false);

    // Localize the script to pass the ajaxurl value
    wp_localize_script('rating-script', 'ratingAjax', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'isLoggedIn' => is_user_logged_in() // Add this line to pass the user login status
    ));

    wp_enqueue_style('rating-style', get_template_directory_uri() . '/css/rating-style.css');
    wp_register_style('main', get_template_directory_uri() . '/css/main.css', array(), false, 'all');
    wp_enqueue_style('main');
    wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=Lora&family=Roboto:wght@900&display=swap', array(), null );
    wp_register_script('script', get_template_directory_uri() . '/js/script.js', array('jquery'),'1.1', true);
    wp_enqueue_script('script');
    wp_enqueue_style( 'font-awesome', 'https://use.fontawesome.com/releases/v6.1.1/css/all.css', array(), null );
}
add_action('wp_enqueue_scripts', 'enqueue_rating_scripts');

// AJAX handler to check if user has already rated
function check_already_rated() {
    if (!is_user_logged_in()) {
        wp_send_json_error(array('alreadyRated' => false)); // User is not logged in, return false
    }

    $post_id = $_POST['post_id'];
    $user_id = get_current_user_id();
    $ratings = get_field('ratings', $post_id);

    foreach ($ratings as $rating) {
        if ($rating['user_id'] == $user_id) {
            wp_send_json_error(array('alreadyRated' => true)); // User has already rated, return true
        }
    }

    wp_send_json_success(array('alreadyRated' => false)); // User has not rated, return false
}
add_action('wp_ajax_check_already_rated', 'check_already_rated');
add_action('wp_ajax_nopriv_check_already_rated', 'check_already_rated');

// AJAX handler for updating ratings
function update_rating() {
    if (!is_user_logged_in()) {
        wp_send_json_error(array('message' => 'Please login first before rating.')); // Send error response if user is not logged in
    }

    $post_id = $_POST['post_id'];
    $rating_value = $_POST['rating_value'];

    // Check if user has already rated
    $user_id = get_current_user_id();
    $ratings = get_field('ratings', $post_id);
    foreach ($ratings as $rating) {
        if ($rating['user_id'] == $user_id) {
            wp_send_json_error(array('message' => 'You have already rated this movie.')); // Send error response if user has already rated
        }
    }

    // Update ACF repeater field for the post
    $new_rating = array(
        'rating_value' => min($rating_value, 5), // Set the rating value to a maximum of 5
        'user_id' => $user_id,
        'timestamp' => current_time('Y-m-d H:i:s')
    );
    $ratings[] = $new_rating;
    update_field('ratings', $ratings, $post_id);

    // Recalculate average rating and update ACF field
    $rating_values = wp_list_pluck($ratings, 'rating_value');
    $average_rating = count($rating_values) > 0 ? round(array_sum($rating_values) / count($rating_values), 2) : null; // Round the average rating to 2 decimal places
    update_field('average_rating', $average_rating, $post_id);

    // Return success response with updated average rating and total ratings
    $response = array(
        'success' => true,
        'average_rating' => $average_rating,
        'total_ratings' => count($ratings)
    );
    wp_send_json($response);
}
add_action('wp_ajax_update_rating', 'update_rating');
add_action('wp_ajax_nopriv_update_rating', 'update_rating');

function display_rating_stars() {
    $post_id = get_the_ID();
    $rating_value = get_field('rating', $post_id);
    $ratings = get_field('ratings', $post_id);
    $average_rating = get_field('average_rating', $post_id);

    // Calculate the maximum number of stars (5)
    $max_stars = 5;

    // Calculate the number of full stars
    $full_stars = 0;
    if (is_array($ratings)) { // Check if $ratings is an array before counting
        $full_stars = min(floor($rating_value), $max_stars); // Limit the full stars to a maximum of 5
    }

    // Output the rating stars HTML
    echo '<div class="rating-stars">';
    for ($i = 1; $i <= $max_stars; $i++) {
        $star_class = ($i <= $full_stars) ? 'star active' : 'star';
        echo '<span class="' . $star_class . '" data-value="' . $i . '" data-post-id="' . $post_id . '">&#9733;</span>';
    }
    echo '</div>';

    // Output the average rating and total ratings
    echo '<div class="rating-info">';
    if (!is_null($average_rating)) {
        echo 'Average Rating: ' . number_format($average_rating, 2);
    }
    if (!is_null($ratings) && is_array($ratings)) { // Check if $ratings is an array before counting
        echo 'Total Ratings: ' . count($ratings);
    }
    echo '</div>';
}


acf-input.js

(function($) {
    acf.add_action('ready', function() {
        // Enable the ACF Number field for the rating ACF field
        $('.acf-field-number input[type="number"]').on('input', function() {
            var $input = $(this);
            var $field = $input.closest('.acf-field');
            var $label = $field.find('.acf-label');

            if ($input.val()) {
                $label.addClass('active');
            } else {
                $label.removeClass('active');
            }
        });
    });
})(jQuery);


single.php

<div class="rating-success-message" style="display: none;">
                        Rating submitted successfully!
                    </div>
                    <div class="rating-error-message" style="display: none;"></div>

ix0qys7i

ix0qys7i1#

updateRatingDisplay(和其他东西)可能无法在您调用它们的地方访问。 AJAX 是异步的,所以你可以在你的函数前面加上async,然后在两个ajax关键字前面加上await,以创建两个单独的ajax语句。我不太确定问题是什么,有很多方法可以解决这个问题,但我重写了你的函数,而没有运行它。除了async,你也可以在 AJAX 调用中设置async: false。请让我知道如果工作。

async function handleRatingSubmission(postID, ratingValue)  {
  if (ratingAjax.isLoggedIn === false) {
    $('.rating-error-message').text('Please login first before rating.').fadeIn().delay(3000).fadeOut();
    return;
  }
        
  let proceed_;
  let second_ajax_success;
        
  proceed_ = await $.ajax({
    url: ratingAjax.ajaxurl,
    type: 'POST',
    data: {
      action: 'check_already_rated',
      post_id: postID
    },
    success: function(response) {
      if (response.alreadyRated) {
        return { 
          value: false, 
          error: false
        }
      } else {
        return { 
          value: true, 
          error: false
        }
      }
    },
    error: function() {
      return { 
        error: true, 
        value: false
      }
    }
  });
        
   if (proceed_.value === true && proceed_.error === false) { 
     second_ajax_success = await $.ajax({
       url: ratingAjax.ajaxurl,
       type: 'POST',
       data: {
         action: 'update_rating',
         post_id: postID,
         rating_value: ratingValue * 2
       },
       success: function(response) {
         if (response.success) {
           return { 
             error: false, 
             value: true
           };
         } else {
           return { 
             value: false, 
             error: false
           };
         }
       },
       error: function() {
         return { 
           error: true, 
           value: false
         }
       }
     });
   } else if(proceed_.value === false && proceed_.error === false) {
     $('.rating-error-message').text('You have already rated this movie.').fadeIn().delay(3000).fadeOut();
   } else { 
     // error - request not sent through
   }
        
    if (typeof second_ajax_success === 'object') {
      if (second_ajax_success.value === true && second_ajax_success.error === false) { 
        $('.rating-success-message').fadeIn().delay(3000).fadeOut();
        updateRatingDisplay(postID, ratingValue);
        var averageRating = parseFloat(response.average_rating).toFixed(2);
        $('.rating-info[data-post-id="' + postID + '"] .average-rating').text('Average Rating: ' + averageRating);
        var totalRatings = response.total_ratings;
        $('.rating-info[data-post-id="' + postID + '"] .total-ratings').text('Total Ratings: ' + totalRatings);
      } else if(second_ajax_success.value === false && second_ajax_success.error === false) {
        // error - request went through but undesired response
      } else { 
        // error - request not sent through
      }
    }
}

字符串
下面是考虑到错误的代码

相关问题