2010-09-17 51 views
1
$(function() { 
     $(".follow").click(function(){ 
     var element = $(this); 
     var I = element.attr("id"); 
     var info = 'id=' + I; 

     $.ajax({ 
      type: "POST", 
      url: "listen.php", 
      data: info, 
      success: function(){} 
      }); 

     $("#follow"+I).hide(); ///showing the remove button after the data has been entered 
     $("#remove"+I).show(); 
     return false; 

     }); 
}); 

的PHP文件listen.php我該如何創建一個成功返回功能?

<?php session_start(); 
include_once ('includes/connect.php'); 

$id = $_POST['id']; 
$follower = $_SESSION['user_id']; 

$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')"); 
?> 

我想要做的就是當我點擊關注按鈕,我要檢查,如果數據已經輸入到數據庫中,顯示的刪除按鈕之前,基本上檢查背景。

回答

1

mysql_query將返回TRUE或FALSE。你可以從PHP腳本中迴應,並讓ajax調用讀取它。

listen.php:

<?php session_start(); 
include_once ('includes/connect.php'); 

$id = $_POST['id']; 
$follower = $_SESSION['user_id']; 

$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')"); 

echo json_encode(array('response'=>$registerlistener)); 
?> 

在你的JavaScript:

$.ajax({ 
type: "POST", 
url: "listen.php", 
data: info, 
dataType: 'json', 
success: function(data){ 
    if(data.response){ 
     // mysql_query returned TRUE 
     $("#follow"+I).hide(); 
     $("#remove"+I).show(); 
    } 
    else{ 
     // FALSE 
    } 
} 
}); 

如果你願意,你可以使用$.post速記:

$.post('listen.php', info, function(data){ 
    if(data.response){ 
     // mysql_query returned TRUE 
     $("#follow"+I).hide(); 
     $("#remove"+I).show(); 
    } 
    else{ 
     // FALSE 
    } 
}, 'json'); 
0

將你想要執行的代碼放入'成功'回調函數中。

$.ajax({ 
    type: "POST", 
    url: "listen.php", 
    data: info, 
    success: function(){ 
     $("#follow"+I).hide(); 
     $("#remove"+I).show(); 
    } 
}); 
0

做這樣的:

listen.php

<?php session_start(); 
include_once ('includes/connect.php'); 

$id = $_POST['id']; 
$follower = $_SESSION['user_id']; 

if($registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')")): 
echo "true"; 
else: 
echo "false"; 
endif; 
?> 

通參數成功的功能,例如 「味精」。無論在listen.php被echo'ed將在味精變量現在

success: function(msg){} 
if(msg == "true") 
{ 
//do something 
} 
else 
{ 
//show error message 
} 
      });