AJAX update MYSQL database using function called from HTML generated from PHP

前端 未结 2 1099
借酒劲吻你
借酒劲吻你 2020-12-19 07:41

I have a php page generating and displaying a table. for the last row in the table i want to display an image with an \'onclick\' function attached. this will send the usern

相关标签:
2条回答
  • 2020-12-19 08:10

    There are some mistakes in this code, let me help you line by line.

    echo "<td> <img id='tblimg' 
    onclick=\'like('" . $row['Username'] . "');\' 
    src='like.jpg' alt='like/dislike image' 
    width='80px' height='30px'></td>";
    

    The javascript function is:

    Escape your quotes for the onclick event first

        function like(user) 
        {
    
            $.ajax({
                url: "update.php",
                type: "POST",
                data: { 'username': user, 'liked': '1' },                   
                success: function()
                            {
                                alert("ok");                                    
                            }
            });
        }
    

    add { and } to the ajax call

    Remove the quotes from table name and fields

    $sql = "UPDATE followers SET Liked = '$Liked' WHERE Username = '$Username'";
    

    in ajax success and after the function begins, you can always print a message to see if your function is being called, and if php script is returning some error, use an alert for that

    UPDATE

    success: function(data){
       alert(data); // this will print you any php / mysql error as an alert                                    
    }
    

    UPDATE 2

    Write your onclick option like this.

    echo "<img onclick=\"like('" . $row['Username']. "');\" 
    src='like.jpg' alt='like/dislike image' 
    width='80px' height='30px' />";
    
    0 讨论(0)
  • 2020-12-19 08:15

    The jQuery.ajax() function expects an object to be passed; you need to use { and } to begin and end your object literal. What you currently have is invalid JavaScript syntax, if you checked your browser's developer tools you'd see an error indicating that. So:

    $.ajax(
        url: "update.php",
        type: "POST",
        data: {
            'username': user,
            'liked': '1'
        },
        success: function () {
            alert("ok");
        }
    );
    

    should be

    $.ajax({ // added {
        url: "update.php",
        type: "POST",
        data: {
            'username': user,
            'liked': '1'
        },
        success: function () {
            alert("ok");
        }
    }); // added }
    
    0 讨论(0)
提交回复
热议问题