2013-03-05 5 views
0

안녕하세요 저는 의견을 달기 위해 버튼을 만들었지 만 클릭 할 때마다 페이지를 다시로드하여 페이지를 다시로드하지 않도록하고 싶습니다. 어디서나 내 질문에 대한 답을 찾을 수 없습니다. 내가 자바 스크립트 또는 AJAX를 사용해야 할 것이라고 이해하지만, 내가 어떻게 붙어있는 코드를 해야할지 모르겠다.PHP MYSQL like button

내 의견 피드가있는 페이지에 있습니다. 페이지의 이름 부재-의 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로 리디렉션합니다. 우리가 jQuery를에 더 쉽게를 대상으로하고 링크 행 ID의 ID를 할 수 있도록

답변

0

PHP/HTML

는 '같은'링크에 클래스를 추가합니다. 이 코드는 마크 업의 다른 곳에서 쉽게 사용할 수있는 간단한 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

우리는하지만 그것은 단지 동일한 코드가 이미 귀하의 질문에이있어하는 아약스 요청을 보내 새로운 스크립트.

마지막 주에

<?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!'; 

?> 

update_likes.php는 mysql_ 기능은 PDO 또는 msqli로 보면 그렇게되지 않습니다.

P. 코드를 테스트하지는 않았지만 잘하면 그냥 작동해야합니다. 여기에 클릭 기능을 변경

UPDATE

시도 :

$('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!'); 
     } 

    }); 
}); 
+0

그 중 하나만 남았습니다. 반환을 제외한 모든 것이 작동합니다. false; 일부는 여전히 링크를 따라 간다. 왜 어떤 생각? –

+0

흠, 그렇게해서는 안되지만 링크의 href를 꺼내고 href 속성으로'#'을 사용하십시오. 브라우저가 여전히 링크를 따라 간다면 최악의 경우 스크롤하여 상단으로 스크롤합니다. 페이지의 – martincarlin87

+0

나는 시도했다. 내가 MAMP를 사용하고 있다는 사실이 될 수 있습니까? 곧 웹 서버로 업로드하여 곧 작동 할 것이라고 기대하고 있습니다. –

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

봅니다 AJAX에서 PHP를 호출하는 JQuery와 사용합니다.

$(".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 json_encode(array(
    "success" => true 
)); 

경우, 당신이 정의 할 수 있습니다 : 그 후, 당신은 응답을 생성하는 echo를 사용할 필요가

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

당신이 jquery 귀하의 웹 사이트에 추가 한 경우를, 당신은 할 수 있습니다 아약스는 이렇게 부릅니다.

먼저 웹 서버에 직접 연결되는 javascript를 호출하도록 같은 링크를 업데이트합니다. 그러므로 다음 링크로 업데이트하십시오 :

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

다음으로 우리는 자바 스크립트를 추가하여 아약스 업데이트 구성 요소를 처리합니다. 서버의 응답을 간단한 경고로 표시했지만 html을 직접 업데이트하거나 인라인 업데이트를 배치 해 볼 수 있습니다. 필요 스크립트 다음 페이지에 추가된다 :

<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은 업데이트가 성공했는지 확인해야합니다.

다음은 likes 업데이트를위한 서버 측 코드입니다. 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); 
?> 

위의 코드는 테스트되지 않았습니다. 따라서 오타/버그/오류가있을 수 있지만 시작하기에 충분해야합니다.

+0

sooo 감사합니다. 나는 이것을 몇 달 동안 알아 내려고 노력했습니다! –

+0

솔기가 하나만 남았으므로 오류가 생길 것입니다. success : function (resp) 왜 그럴까요? –