Using jQuery .ajax for a voting script. How do I update MySQL DB after successful vote?
I'm assuming I have to put something in the success option. However what I have isn't working.
I declare this JS function on the page:
<script type="text/javascript">
function performAjaxSubmission() {
$.ajax({
ur开发者_StackOverflow中文版l: 'addvotetotable.php',
method: 'POST',
data: {
},
success: function() {
}
});
}
</script>
Then in the ajax call which is working properly I declare this for the success:
success: function(data) {
performAjaxSubmission();
},
addvotetotable.php looks like:
<
?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());
}
?>
You have to provide a value that you want to store in your database in the "data" of the ajax-request. Than you can use this in your php-code using $_POST["something"], check if it's valid... and return f.e. html or json which you than handle in the success-function.
<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>
What this does is post data of the vote (it's value) to the php-file. There you can read it with $_POST["theVoteValue"]
and put it in the database. You check if the value is valid and may insert, else you return an error-message or something so that in javascript you can notify the user of it's failure.
精彩评论