无法更改AJAX getJSON .done上的按钮UI [英] Unable to change button UI on AJAX getJSON .done

查看:49
本文介绍了无法更改AJAX getJSON .done上的按钮UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建将帖子添加到收藏夹并发布在 codereview 后,我必须进行改进我的代码如下更改代码后,单击按钮时UI不会改变

After creating add post to favorite and posted at codereview i had to improve my code as bellow, And after changing code the button UI doesn't change when clicked

post_page.php

<?php
$email = 'user@mail.com';
// Query to get the user_id
$stmt = $conn->prepare('SELECT memberID FROM members WHERE email = :email AND active="Yes" ');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch();
$mbid = $row['memberID'];

$pid = '4';
// Query to Get the Director ID
$stmt = $conn->prepare('SELECT * FROM allpostdata WHERE id =:id');
$stmt->execute(array(':id' => $pid));
$result = $stmt->fetchAll();
foreach ($result as $row) {

    echo "<p>Director: " . $row['tit'] . "</p> ";
    $fav_image = checkFavorite($mbid, $pid, $conn);
    echo "Favorite? : " . $fav_image . "";
}

function checkFavorite($mbid, $pid, $conn) {
$stmt = $conn->prepare("SELECT * FROM favorite WHERE memberID=:mid AND id=:id");
$stmt->execute(array(':mid' => $mbid, ':id' => $pid));
$count = $stmt->rowCount();
if ($count == 0) {
    echo "<div class='button btn btn-block btn-outline-danger' method='Like'  data-user=" . $mbid . " data-post=" . $pid . "> Add<i class='mi mi_sml ml-2' id=" . $pid . ">favorite_border</i></div>";
} else {
    echo "<div class='button btn btn-block btn-outline-danger' method='Unlike'  data-user=" . $mbid . " data-post=" . $pid . ">Remove<i class='mi mi_sml ml-2' id=" . $pid . ">favorite</i></div>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script>

    $(document).ready(function () {
            $('.button').click(function (e) {
                e.preventDefault();
                $.getJSON('favs.php',
                        {user_id: $(this).attr('data-user'),
                            director_id: $(this).attr('data-post'),
                            method: $(this).attr('method')})
                        .done(function (json) {
                            switch (json.feedback) {
                                case 'Like'   :
                                    $(this).attr('method', 'Unlike');
                                    $(this).html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button
                                    break;
                                case 'Unlike' :
                                    $(this).html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button');
                                    $(this).attr('method', 'Like');
                                    break;
                                case 'Fail'   :
                                    alert('The Favorite setting could not be changed.');
                                    break;
                            }
                        })
                        .fail(function (jqXHR, textStatus, error) {
                            alert("Error Changing Favorite: " + error);
                        });
            });
        });
</script>

favs.php

<?php

include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
include("$_SERVER[DOCUMENT_ROOT]/classes/function.php");

$method = clean_input($_GET['method']);
$user_id = clean_input($_GET['user_id']);
$director_id = clean_input($_GET['director_id']);

switch ($method) {
    case "Like" :
        $query = 'INSERT INTO favorite (memberID, id) VALUES (:mID, :pID)';
        break;
    case "Unlike" :
        $query = 'DELETE FROM favorite WHERE memberID=:mID and id=:pID';
        break;
}
$feedback = 'Fail'; // start with pessimistic feedback
if (isset($query)) {
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':mID', $user_id, PDO::PARAM_INT, 12);
    $stmt->bindParam(':pID', $director_id, PDO::PARAM_INT, 12);
    if ($stmt->execute()) {
        $feedback = $method;
    } // feedback becomes method on success
}
echo json_encode(['id' => $director_id,
    'feedback' => $feedback]);
?>

我的问题是单击按钮时,当ajax返回成功时,按钮应更改其UI.在我的情况下,它在页面加载时没有变化,即使单击按钮并且ajax返回成功后,它仍显示 Add 仍然是相同的.

My problem is when button is clicked and when ajax return success the button should change its UI. where else in my case its not changing when on page load it show Add even after clicking on button and ajax return success still it is same.

推荐答案

您的代码的问题是 $(this),即:在ajax成功函数中,jquery无法找到被单击的元素以及在哪里应用所需的更改.为了解决这个问题,您可以将 $(this)存储在某些变量中并使用它.如下所示:

The problem with your code is $(this) i.e: In ajax success function jquery is not able to find which element is clicked and where to apply required changes. To solve this you can store $(this) in some variable and use the same. Like below :

$('.button').click(function(e) {
  //getting current element which is clicked
  var button = $(this);
  e.preventDefault();
  $.getJSON('favs.php', {
      user_id: $(this).attr('data-user'),
      director_id: $(this).attr('data-post'),
      method: $(this).attr('method')
    })
    .done(function(json) {
      switch (json.feedback) {
        case 'Like':
          button.attr('method', 'Unlike');
          button.html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button
          break;
        case 'Unlike':
          button.html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button');
          button.attr('method', 'Like');
          break;
        case 'Fail':
          alert('The Favorite setting could not be changed.');
          break;
      }
    })
    .fail(function(jqXHR, textStatus, error) {
      alert("Error Changing Favorite: " + error);
    });
});

这篇关于无法更改AJAX getJSON .done上的按钮UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆