Amir Meimari
Amir Meimari

Reputation: 538

error in updating mysql with $.post using jquery

i wanna have like for my blog posts, it should work like this: user will click on something and it increase that number by +1 and store it in data base, i have a column named post_like in my db. but after increase 0 to 1 (when i try to increase from 1 to 2 or more) i get error. jquery:

 $("#insert_like").click(function(e){
        alert('s')
        var like = $("#insert_like").val();
        like += 1;
        var post_id = $("#post_id").val();
        $.post("./inc/like.php", {
            like: like,
            post_id: post_id
        }, function(data, status){
            $("#insert_like").text(data);
            like = 0;
        });
    });

php:

<?php
if (isset($_POST['like'])) {
    require_once 'db.inc.php';
    $like = $_POST['like'];
    $post_id = $_POST['post_id'];




    $q = "UPDATE posts set post_like = ? WHERE post_id=? LIMIT 1";
    $stmt = $conn->prepare($q);
    $stmt->bind_param('ii', $like, $post_id);
    $stmt->execute();
    if ($stmt->affected_rows == 1) {
        echo "$like";
    } else {
        echo "error: $stmt->error";
    }
    $stmt->close();
    $conn->close();
} else {
    header('Location: ../home.php');
}

html:

<p>Post like: <span id="insert_like" style="cursor: pointer"><?php echo $post_like ?></span> </p>

Upvotes: 2

Views: 54

Answers (1)

Kishen Nagaraju
Kishen Nagaraju

Reputation: 2200

You can pass the Post Id from javascript and update the likes in the backend. Consider below example:

$("#insert_like").click(function(e){
    $.post("./inc/like.php", {
        post_id: $("#post_id").val()
    }, function(data, status){
        $("#insert_like").text(data);
        like = 0;
    });
});

and in the backend

<?php
    if (isset($_POST['like'])) {
        require_once 'db.inc.php';
        $post_id = $_POST['post_id'];

        $q = "UPDATE posts SET post_like = (post_like + 1) WHERE post_id = ?";
        $stmt = $conn->prepare($q);
        $stmt->bind_param('i', $post_id);
        $stmt->execute();
        if ($stmt->affected_rows == 1) {
           // get the updated likes and return as response.
        } else {
           echo "error: $stmt->error";
        }
        $stmt->close();
        $conn->close();
    } else {
        header('Location: ../home.php');
    }

Hope this helps.

Upvotes: 2

Related Questions