2011-09-22 29 views
0

我假設我必須把東西放在成功選項。然而,我有沒有工作。將jQuery .ajax用於投票腳本。如何在投票成功後更新MySQL數據庫?

我宣佈這個JS網頁上的功能:

<script type="text/javascript"> 
function performAjaxSubmission() { 
     $.ajax({ 
      url: 'addvotetotable.php', 
      method: 'POST', 
      data: { 
      }, 
      success: function() { 
      } 
     }); 

     } 
</script> 

然後在AJAX調用,它工作正常,我宣佈本作的成功:

success: function(data) { 

      performAjaxSubmission(); 
}, 

addvotetotable.php樣子:

<

?php 
// If user submitted vote give the user points and increment points counter 

require_once("models/config.php"); 

//Check to see if there is a logged in user 
    if(isUserLoggedIn()) { 
    $username_loggedin = $loggedInUser->display_username; 
    } 

    if (strlen($username_loggedin)) { 
    include_once "scripts/connect_to_mysql.php"; 
    $query = mysql_query("SELECT vote FROM points_settings WHERE id=1")or die (mysql_error()); 
    while($info = mysql_fetch_array($query)){ 

      $points_value=$info['vote']; 
    } 
    include_once "scripts/connect_to_mysql.php"; 
     $query = mysql_query("INSERT INTO points (id,username,action,points) VALUES ('','$username_loggedin','vote','$points_value')")or die (mysql_error 

()); 
     include_once "scripts/connect_to_mysql.php"; 
     $query = mysql_query("UPDATE userCake_Users SET points=points + $points_value WHERE Username='$username_loggedin'")or die (mysql_error()); 
    } 

    ?> 
+0

呃,看起來很強大的遞歸... –

回答

2

您必須提供一個值,以便將其存儲在數據庫中的ajax請求的「數據」中。比你可以在你的php代碼中使用$ _POST [「something」],檢查它是否有效......並返回f.e. HTML或JSON,你比在成功功能處理。

<script type="text/javascript"> 

function onSubmitVote() 
{ 

     $.ajax({ 
      url: 'addvotetotable.php', 
      method: 'POST', 
      data: "theVoteValue=" + <read_your_vote_value_here>, 
      success: function(result) { 
      >>>return something in your addvotetotable.php which indicate success and show a message whether the vote was successful or not.<<< 
      } 
     }); 

     return false; // prevent submit if it is a submit-type button. 

} 
</script> 

這是幹什麼的投票數據(它的價值)的PHP文件。在那裏,你可以用$_POST["theVoteValue"]來讀取它並將其放入數據庫中。您檢查值是否有效並可能會插入,否則您會返回一條錯誤消息或其他內容,以便在JavaScript中可以通知用戶它失敗。

+0

我真正需要做的就是運行addvotetotable.php一旦投票的ajax完成。有沒有其他方法可以在成功函數中調用php文件? – PaperChase

+0

你通常使用ajax-request來調用一個php,所以我不確定你爲什麼要對php文件執行一個請求,並且只對你想要做的事情成功。我想你只是想用你想存儲的數據做一個請求,然後在成功上展示一些東西。你究竟想要做什麼? – JNDPNT

+0

我正在使用投票腳本,它使用ajax註冊投票而不重新加載頁面。我注意到他們使用的ajax函數具有成功功能。在那裏我想打電話給我的PHP文件在我的mysql數據庫中註冊投票。 – PaperChase