PHP MYSQL之类的按钮

时间:2013-03-05 09:50:11

标签: php javascript mysql ajax jquery

嗨我已经为评论提供了一个类似的按钮,但是每次我点击它都会重新加载我想要的页面,以便它不会重新加载页面。我无法在任何地方找到我的问题的答案。我明白我将不得不使用javascript或AJAX,但因为我不知道如何编码,我被卡住了。

这是我的评论供稿所在的页面。页面的名称是member-index.php

<a href=\"like-exec.php?id=".$rows['ID']."&members_id=".$_SESSION['SESS_MEMBER_ID']."\">like</a>

,这是在执行代码的页面上(如-exec.php)

<?php
require('../config/connect.php');
require('../config/config.php');

$sql = "UPDATE comments set `like` = `like`+1 where `ID` = '$_GET[id]'";
$result=mysql_query($sql);


$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("likes", $con);

mysql_query("INSERT INTO likes (members_id, comm_id) VALUES(".$_SESSION['SESS_MEMBER_ID'].", $id)");


mysql_close($con);
header("location: success.php");

?>

代码完成后,它会被发送到susses.php,然后将其重定向到member-index.php。

3 个答案:

答案 0 :(得分:0)

<强> PHP / HTML

在“喜欢”链接中添加一个类,以便我们可以更轻松地在jQuery中定位它,并使链接的id成为行id。同样值得检查的是,页面上的其他地方没有数字ID,因为这些ID很容易在标记的其他地方使用。

<a class="like" id="<?php echo $rows['ID']; ?>" href=\"like-exec.php?id=".$rows['ID']."&members_id=".$_SESSION['SESS_MEMBER_ID']."\">like</a>

<强>的jQuery

$('a.like').click(function() {
    // triggered when like link is clicked

    // get the id of this link
    var id = $(this).attr('id');

    // make the AJAX request to the PHP script that updates the database table

    $.ajax({
        type: "GET",
        url: update_likes.php,
        dataType: 'html',
        data: ({ id: id }), // first id is the name, second is the actual id variable we just created
        beforeSend: function(data) {
            // you can do stuff in here before you send the data, display spinner gif etc
            alert('sending!');
        },
        success: function(data) {
            // same here but when the ajax request is successful
            // the data variable is coming from the echo of your PHP script
            alert(data);
        },
        complete: function(data) {
            // yet again but on completion
            alert('complete!');
        }

    });

    // stops the browser following the link (href) in the a tag
    return false;

});

<强> PHP

我们发送ajax请求的新脚本,但它与您在问题中已有的代码相同。

<强> update_likes.php

<?php
require('../config/connect.php');
require('../config/config.php');

// not sure if session_start(); is in your config but you will need it
// in this script somewhere to do your second query.

// $_GET['id'] is now coming via ajax

$sql = "UPDATE comments set `like` = `like`+1 where `ID` = '$_GET[id]'";
$result=mysql_query($sql);


$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("likes", $con);

mysql_query("INSERT INTO likes (members_id, comm_id) VALUES(".$_SESSION['SESS_MEMBER_ID'].", $id)");


mysql_close($con);

// header("location: success.php");
// don't need this anymore

// only echo one string from an ajax request so if you need more do some
// concatenation
echo 'successfully updated db!';

?>

最后,不推荐使用mysql_函数,因此请查看PDO或msqli。

P.S。我没有测试过代码,但是希望它应该可以正常工作。

<强>更新

尝试将点击功能更改为:

$('a.like').click(function(e) {
    // triggered when like link is clicked


    // stops the browser following the link (href) in the a tag
    e.preventDefault();

    // get the id of this link
    var id = $(this).attr('id');

    // make the AJAX request to the PHP script that updates the database table

    $.ajax({
        type: "GET",
        url: update_likes.php,
        dataType: 'html',
        data: ({ id: id }), // first id is the name, second is the actual id variable we just created
        beforeSend: function(data) {
            // you can do stuff in here before you send the data, display spinner gif etc
            alert('sending!');
        },
        success: function(data) {
            // same here but when the ajax request is successful
            // the data variable is coming from the echo of your PHP script
            alert(data);
        },
        complete: function(data) {
            // yet again but on completion
            alert('complete!');
        }

    });
});

答案 1 :(得分:0)

<a class="like" href=\"like-exec.php\" comment-id=".$rows['ID']." members-id=".$_SESSION['SESS_MEMBER_ID']."\">like</a>

尝试使用JQuery在AJAX中调用PHP。

$(".like").click(function(){

    $.ajax({
      url: $(this).attr("href"),
      type: "GET",
      data: { comment-id: $(this).attr("comment-id"), members-id: $(this).attr("members-id")},
      success:function(result){

         if(result.success) {
            // Success
         }else{
            // Not success
         }

      },
      error: function(request,status,error){
         // Request error
      }
    });    

});

在PHP中,您可以使用$_GET["comment-id"]$_GET["members-id"]获取变量。 当您的脚本成功时,您可以在数组中定义信息,并且可以使用JSON对其进行编码。之后,您必须使用echo生成响应:

echo json_encode(array(
   "success" => true
));

如果您的脚本没有成功,您可以定义:

echo json_encode(array(
    "success" => false,
    "reason" => "some reason"
));

答案 2 :(得分:0)

如果您在网站上添加了jquery,则可以进行这样的ajax调用。

首先,我们更新类似的链接,以便它调用javascript,而不是直接链接到网络服务器。因此,请将您的链接更新为:

<a href=\"like-exec.php?id=".$rows['ID']."&members_id=".$_SESSION['SESS_MEMBER_ID']."\" onclick="updateLike($(this));return false;">like</a>

然后我们添加javascript来处理ajax更新组件。我已将服务器的响应作为简单警报,但您可以尝试直接更新html或放置一些内联更新。需要在页面中添加以下JavaScript:

<script type="text/javascript">
function updateLike(elm)
{
$.ajax({
  type:'GET',
  url: elm.attr('href'),
  error: function(xhr, status, err) {
      // TODO : User friendly error message on ajax fail
      alert("Request Error :" + xhr + status + err);
  }

  success: function(resp) {
      // ajax operation was successful - confirm the like was okay
      if (resp.success) {
         window.location(resp.redirect);
      } else {
         // TODO : User friendly error message on update fail
         alert("Like failed : " + resp.error);
      }
  }
}
</script>

$.ajax()函数执行ajax操作。 error属性处理客户端无法与服务器通信或未获得有效响应的问题。 success属性处理服务器响应的实例。 success还需要检查更新是否成功。

以下是喜欢更新的服务器端代码。您已使用mysql_*函数,因此我保持这些功能完好无损。但是,请记住,这些函数现已弃用,而不是MySQLi。您应该考虑更新代码以反映这一点。

<?php
require('../config/connect.php');
require('../config/config.php');

$error = "";

$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con)
{
   $error = "Unable to connect to database.";
} else {

   // Check the database is available
   $db = mysql_select_db("likes", $con);

   if (!$db)
   {
      $error = "Unable to select like database.";
   } else {
      // Moved update to after connecting with database
      $sql = "UPDATE comments set `like` = `like`+1 where `ID` = '" . $_GET[id] . "'";
      $result = mysql_query($sql);
      if (!$result) { // Check query is successful
         $error .= "Error when updating comment likes.";
      }

      $result = mysql_query("INSERT INTO likes (members_id, comm_id)
      VALUES(".$_SESSION['SESS_MEMBER_ID'].", $id)");
      if (!$result) { // Check insert is successful
         $error .= "Error when inserting member likes.";
      }
   }

   mysql_close($con);
}

// Convert output to a JSON object for jquery to handle
$resp = new Object();
if ($error == "")
{
   $resp->success = true;
   $resp->redirect = "success.php";
} else {
   $resp->error = $error;
   $resp->success = false;
}

echo json_encode($resp);
?>

上面的代码未经测试;所以可能存在拼写错误/错误/错误但它应该足以让你开始。