用PHP脚本交流javascript

用PHP脚本交流javascript

问题描述:

I am trying to send data from Javascript to a php script. I am new to PHP,javascript and JSON etc. I am tryin to use jQuery Upvote plugin. I am reading the documentation from readme.md here. However, I find it too vague for my understanding.

I have added the following code in HTML body. The plugin is working fine in front-end.

<div id="topic" class="upvote">
    <a class="upvote"></a>
    <span class="count">0</span>
    <a class="downvote"></a>
    <a class="star"></a>
</div>
<div id="output"> </div>
<script language="javascript">
var callback = function(data) {
    $.ajax({
        url: '/vote',
        type: 'post',
        data: { id: data.id, up: data.upvoted, down: data.downvoted, star: data.starred }
    });
};
$('#topic').upvote({id: 123, callback: callback});
</script>

Can someone please tell how should I write the php counterpart so as to get the information about change of state of plugin? I think it is related to json maybe but I am stuck here..

EDIT: As per the suggestion, I have modified a bit of code and wrote PHP script. In above code I have changed URL to my PHP script url: 'voter.php'.

This is the PHP code (in brief) :

<?php require_once('Connections/conn.php'); ?>
mysql_select_db($database_conn, $conn);
if ($_POST['up']!=0){
$query_categories = "UPDATE user SET score=1 WHERE u_id =5";
$categories = mysql_query($query_categories, $conn) or die(mysql_error());
}
else if ($_POST['down']!=0) {
    $query_categories = "UPDATE user SET score=-1 WHERE u_id =5";
$categories = mysql_query($query_categories, $conn) or die(mysql_error());

}

The database connection is working fine, but still the database values are not updated by above code..

Your script sends AJAX Post request to the php script. You can access those post variables like this, using $_POST[] array:

$id = $_POST['id'];
$up = $_POST['up'];
$down = $_POST['down'];
$star = $_POST['star'];

Then you can populate the mysql table, etc.