Change img properties (src, alt…) based on AJAX success (and fix my ajax ;) )

江枫思渺然 提交于 2021-01-29 16:36:45

问题


The image link I'm using:

echo "<br/><div class='right' id='post" . $id . "'>
<img id='thumb' src='/images/like.png' title='Like it?' alt='Like button' 
          onClick='likeButton(" . $id . ");'>( " . getLikes($id) . " )</div><br/>";

and the JavaScript is:

function likeButton(id) {
    $.ajax({
        url: "../../likes/" + id, 
        type: "post", 
        data: {
            id: id},
        success: function(likes) {
        $('#post' + id).html(likes);
    }}); 
}

"likes" is the PHP function that adds the click to the db, and it also returns the number (getLikes($id)).

But there's a couple things wrong here. When I click, the image disappears and I'm only left with the number

Instead, I need it to keep showing the image (and the paranthesis around the number) - but change the image src and alt if the PHP function getLikes($id) == "true".

Any takers?


回答1:


Instead of replacing the content of the ENTIRE post, just change the value of the likes:

( " . getLikes($id) . " ) => <span class="likes">( " . getLikes($id) . " )</span>

and

$(`#post${id} .likes`).text(`(${likes})`);

EDIT: Follow-up question:

You asked about preventing clicking more than once. You can add a flag to know they have already clicked.

NOTE: This will only one until they reload the page, it's not a great solution if you really want to block them. Your server should prevent it server-side in PHP instead (e.g. check if they have already like it before incrementing the count by user id + post id).

function likeButton(id) {
    if ($('#post' + id).hasClass('already-liked')) {
        return;
    }
    $('#post' + id).addClass('already-liked');

    $.ajax({
        url: "../../likes/" + id, 
        type: "post", 
        data: {
            id: id},
        success: function(likes) {
        $('#post' + id).html(likes);
    }}); 
}


来源:https://stackoverflow.com/questions/62078390/change-img-properties-src-alt-based-on-ajax-success-and-fix-my-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!