Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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 username for the selected row to a script that will use AJAX to update a database. The table displays fine but the AJAX is not working. my php to display the image is:

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:

<script type="text/javascript" >

        function like(user) 
        {

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

</script>       

And here is update.php:

<?php


$con=mysqli_connect("","sam74","********","sam74");

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$Username = $_POST['username'];
$Liked = $_POST['liked'];   

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

if (!mysqli_query($con,$sql))
{
    die('Error: ' . mysqli_error($con));
}

mysqli_close($con);

?>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...