My ajax function is not working, i have tried these codes [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So our project is to make an ordering website, we had everything down design-wise. Now that the designing is done, we're now focused to the function of the website. I've done a different approach where i'm able to insert an item into the database but the php page reloads everytime I add an item.
I want to make my ordering page be able to add an item and not reload, i've searched on how to do it and it says i have to use a javascript or ajax, this is what i've tried so far as i don't actually know javascript
this is my ordering php page
function onSubmit() {
$.ajax({
url: 'inserttocart.php',
method: 'post',
data: $("#orderid").serialize(),
success: function(response) {
alert(response);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="orderid">
<p><br>Your choice of 1 marinade: </p>
<input class="chkb1" type="checkbox" name="choice1" value="Bulgogi">&nbsp Bulgogi<br>
<input class="chkb1" type="checkbox" name="choice1" value="Galbi">&nbsp Galbi<br>
<input class="chkb1" type="checkbox" name="choice1" value="Gochujang">&nbsp Gochujang<br>
<input class="chkb1" type="checkbox" name="choice1" value="JRAMS">&nbsp JRAMS Special
<button class="cart-button" type="button" onclick="onSubmit()" id="addtocartbtn" name="beefbtn">
<span class="add-to-cart">Add to Cart</span>
<span class="added">Added</span>
<i class="fas fa-shopping-cart"></i>
<i class="fas fa-box"></i>
</button>
</form>
This is my inserttocart.php
$connect = mysqli_connect("localhost", "root", "", "pigmedb");
if ($connect == false) {
die("ERROR: Could not connect. ".mysqli_connect_error());
}
if (isset($_POST['choice1']) && (isset($_POST['beefbtn']))) {
$marinade = ($_POST['choice1']);
if ($connect == false) {
die("ERROR: Could not connect. ".mysqli_connect_error());
}
if ($marinade == "Bulgogi") {
$sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Bulgogi Marinated)'";
}
elseif($marinade == "Galbi") {
$sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Galbi Marinated)'";
}
elseif($marinade == "Gochujang") {
$sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (Gochujang Marinated)'";
}
elseif($marinade == "JRAMS") {
$sqlresult = "SELECT foodname FROM pigme_cart WHERE foodname='Beef Set (JRAMS Special Marinated)'";
}
$result = mysqli_query($connect, $sqlresult);
if (mysqli_num_rows($result) > 0) {
// row exists
echo "Item Already Added";
mysqli_close($connect);
} else {
if ($marinade == "Bulgogi") {
$sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Bulgogi Marinated)', '1', '399')";
}
elseif($marinade == "Galbi") {
$sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Galbi Marinated)', '1', '399')";
}
elseif($marinade == "Gochujang") {
$sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (Gochujang Marinated)', '1', '399')";
}
elseif($marinade == "JRAMS") {
$sql = "INSERT INTO pigme_cart(foodname, quantity, price) VALUES ('Beef Set (JRAMS Special Marinated)', '1', '399')";
}
else {
echo "Please select one of the marinade of the Beef Set.";
}
if (mysqli_query($connect, $sql)) {
echo "Added to Cart";
} else {
echo "ERROR: Could not able to execute $sql. ".mysqli_error($connect);
}
mysqli_close($connect);
}
}
My goal is to prevent the first page from reloading as this is a cart, but at the same time, its able to insert an item into the mysql database. pls help thank you

Buttons aren't included in the result of .serialize(), since it doesn't know which button was clicked. So $_POST['beefbtn'] won't be set.
You can add it yourself.
data: $("#orderid").serialize() + '&beefbtn=1'
Or you could remove that check from the PHP.

Related

AJAX request failing to be recognized as POST by PHP script [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to post a form to a PHP script, and it is getting stuck at validating the request as a POST request, and thus it exits from the PHP script. The AJAX request returns as successful, but the data returned from the database says the recognition of the request as POST failed. I've tried changing the content types etc, to no avail.
JS:
$(document).ready(function() {
$("#delete4").on('click', function(e) {
e.preventDefault();
var ok = confirm('Are you sure you want to delete this?');
if (ok == true)
{
console.log("true")
var data = $("#form4").serialize();
$.ajax({
data: data,
type: "post",
url: "delete_AJAX.php",
success: function(data) {
console.log("successfully deleted");
console.log(data);
//$("#div4").remove();
},
error: function(data) {
alert("fail");
console.log(data);
}
});
} else {
return;
}
});
});
HTML:
<form type="text" name="form4" id="form4" action="delete_AJAX.php" method="post">
<div class="aligner">
<button type="button" class="button_div" name="edit" onclick="send(52)">Edit</button>
<button type="button" class="button_div" id="delete4">Delete</button>
<button type="button" class="button_div" name="read" onclick="send2(52, 13)">See</button>
</div><br>
<input type="hidden" id="hidden_c4" value="13" name="hidden_c">
<input type="hidden" id="hidden_bid4" name="hidden_bid" value="52">
</form>
PHP:
require_once("db.php");
if ($_REQUEST['REQUEST_METHOD'] === 'POST')
{
$bid = $_POST['hidden_bid'];
echo "passed request";
$sql = "SELECT * FROM xxx WHERE yyy = $bid";
$result = mysqli_query($connection, $sql);
if ($result === false)
{
die("f1");
}
$resultCheck = mysqli_num_rows($result);
if (!resultCheck > 0)
{
echo "ERROR NO RESULT";
exit();
};
$row = mysqli_fetch_assoc($result);
$delete_cover = $row['cover'];
unlink($delete_cover);
// updating table row
$sql2 = "DELETE FROM xxx WHERE (yyy=?);";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql2))
{
header("Location: ../create.php?error&prepare1111");
exit();
}
else
{
$stmt->bind_param("i", $bid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$connection->close();
echo "successfully deleted";
}
} else {
echo "FAILURE TO REQUEST";
}
So I keep consistently getting failure "FAILURE TO REQUEST", and when I remove any barrier to the script, post is shown as empty, and the variables arent set. Thus it stops at the "f1" error. Any help would be amazing!! Thankyou!
You seem to be using the wrong global variable for the "REQUEST_METHOD".
Instead of $_REQUEST['REQUEST_METHOD'] use $_SERVER['REQUEST_METHOD']
In the conditional,
$_REQUEST['REQUEST_METHOD'] should be replaced with $_SERVER['REQUEST_METHOD'].
Maybe could this help
if( $_POST ) {
echo 'posted';
//do some stuff
}

Run separate queries in MySQL using a single link

I have created that toggles a material icon to on/off.
When the icon is off I need to run a delete query.
When the icon is on I need to run a insert query.
I know I need to use AJAX and am still new to it.
What I am having trouble understanding is whether I refernece the current PHP file or some other php file. Iknow I have to write my query and execute it in a PHP file, but not sure to do that. I do not want to reload the pagebecuase I lose other information by doing so.
I basically owuld like to update the icon and execute the required SQL stmnt.
Any help is appreciated.
What I have so far:
JAVASCRIPT:
//update the favorites icon
function updateFavorites(id){
if($(this).find('#staricon'+id)){
if($('#staricon'+id).hasClass('star-color')) {
$('#staricon'+id).removeClass('star-color');
//update the table
deleteFavorites();
}
else {
$('#staricon'+id).addClass('star-color');
addFavorites();
}
}
}
//delete the item from the table
function deleteFavorite(){
$.ajax({
type: "POST",
url: "somePHPFile.php",
cache: false,
data:{id:'#staricon'+id},
}).done(function( msg ) { console.log(msg);
});
}
PHP:
//check to see if this is a favorite
$query = "SELECT * FROM favorites WHERE story_id = " . $story_id;
$result = mysqli_query($conn, $query);
$is_fav = mysqli_num_rows($result);
if ($is_fav > 0) {
echo '<a class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'" class="star-color" onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
else {
echo '<a class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'" onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
I have update my code to reflect the following:
JAVASCRIPT:
function updateFavorites(id){
if($(this).find('#staricon'+id)){
if($('#staricon'+id).hasClass('star-color')) {
$('#staricon'+id).removeClass('star-color');
$.ajax({
type: "POST",
url: "showStoryCards.php",
data: {
id: $(this).data(id),
enabled: !$(this).hasClass('star-color') //delete
},
})
}
else {
$('#staricon'+id).addClass('star-color');
$.ajax({
type: "POST",
url: "showStoryCards.php",
data: {
id: $(this).data("id"),
enabled: $(this).hasClass('star-color') //insert
},
})
}
}
PHP:
echo $story_title ;
$query = "SELECT count(*) FROM favorites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->get_result();
$is_fav = mysqli_num_rows($result);
if ($is_fav == 0) {
echo '<a class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'" class="star-color"
onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons "
title="Favorite" >star</i></span></a>';
}
else {
echo '<a class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'" onclick="updateFavorites(' . $story_id .
')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
if (isset($_POST['enabled'])){
if($_POST['enabled']) { // INSERT query
$sql = "INSERT INTO favorites VALUES( " . $id . ", '1') ";
$sql->execute();
} else {// Delete query
}
}
My icons update to the appropriate on /off colors but I still cannot get the query to fire. It does not even appear that the call back to the PHP page is functioning as I cannot retrieve the $_POST.
Use prepared statements because you're opening yourself to injection attacks.
Try this query
$query = "SELECT * FROM favourites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->getResult();
print_r($result);
Simplify it all.
$(document).ready(function() {
$('#staricon').on('click', function() {
// Prevent multiple clicks before the first one finishes.
// There is probably a more elegant way to do this.
if(active){
return;
}
active = false;
//console.log($(this).hasClass('star-color'));
//console.log($(this).data("id"));
$.ajax({
type: "POST",
url: "somePHPFile.php",
data: {
id: $(this).data("id"),
enabled: !$(this).hasClass('star-color')
},
}).done(function(msg) {
active = true;
$(this).toggleClass('star-color');
console.log(msg);
});
});
});
/*
PHP
// Use ID and enabled to add or delete from db.
if($_POST['enabled']) {
// INSERT query
} else {
// Delete query
}
*/
div.star-color {
background-color: #FF00FF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="staricon" data-id="1" class="star-color">Test</div>

Session not sending correctly through AJAX

I have the following code that I thought worked correctly, but it turns out the users session is not being sent correctly. Let's say I was on trying to make a post, it does not take my id, it takes the id of the last user who registered for my site. Why would this be?
I have this as my $userid variable and it should be taking my session. I am initializing the session at the top of the page.
What am I doing wrong?
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP and Form
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
}
$user_stmt->store_result();
$user_result = array();
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
UPDATE: PHP file to show an example
// $announcement_user_id= $_POST['user_id'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $userid, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
You're selecting all of the users:
SELECT `id` FROM users
So when you get one record from that result, it's probably going to coincidentally be the latest record in the table.
You're trying to bind a parameter to i:
$user_stmt->bind_result($user_id);
so maybe you meant to have a WHERE clause?
SELECT `id` FROM users WHERE `id` = ?
Though, that seems... unnecessary. Since you already have the ID. You seem to be posting the ID from client-side, and keeping it in session state, and getting it from the database. So it's not entirely clear what you're even trying to do here. But one thing that is clear is that query is going to return every record from that table.

How to prevent people from spamming an ajax form [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
My problem is I have a vote system similar to the one of Stack Overflow. My problem is that a person can spam the vote up button which makes it glitch and make it submit more times than it’s supposed to. For example, if there are 10 up votes on a post, I could repeatedly click the vote up button and the it would add two or three up votes instead of one. Similarly I could do this with the down vote button. How do I prevent this?
Index.php:
<?php
session_start();
require('db.php');
$pid = 2;
$uid = $_SESSION['id'];
$sql = mysqli_query($con, "SELECT * FROM posts WHERE pid = '$pid'"); //check to see how many likes the post has
$r = mysqli_fetch_assoc($sql);
$body = $r['body'];
$likes = $r['likes'];
$sql2 = mysqli_query($con, "SELECT * FROM likes WHERE pid = '$pid' AND uid = '$uid'"); //check to see if user has voted
$n = mysqli_num_rows($sql2);
if ($n == 0) {
//user hasn't liked or down vote anything yet
$liked = "no";
} else {
if ($n > 1) {
//like scammed
echo "<script>alert('Stop spamming for votes. You are banned for spam.')</script>";
exit("You have been banned for spam");
//This isn't fool proof though, and I don't want to ban people for this. It would be best if I could just prevent the vote scam in the first place
}
$r = mysqli_fetch_assoc($sql2);
$type = $r['like_type'];
if ($type == '0') {
$liked = "liked";
} else {
$liked = "disliked";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="//code.jquery.com/jquery-latest.min.js"></script>
<style>
.selected {
color: red;
}
</style>
</head>
<body>
<div class="post">
<p><?php echo $body; ?></p>
</div>
<div class="likes">
Upvote
<span id="votes-<?php echo $pid; ?>"><?php echo $likes; ?></span>
Downvote
</div>
</body>
Javascript vote() function
function vote(type, pid, uid, id, voteId) {
var vote = $('#'+ id);
if (vote.hasClass('selected')) {
//user voted for this
$.post("vote.php", {pid: pid, uid: uid, type: type, vote: 'reset'}, function(d) {
if (d == '0' || d == '1') {
vote.removeClass('selected');
var votes = $('#' + voteId);
var num = votes.text();
if (d == '1') {
votes.text(++num);
} else {
votes.text(--num);
}
} else {
alert('An error occurred')
}
});
} else {
var upVoteId = $('#up-' + pid);
var downVoteId = $('#down-' + pid);
if (upVoteId.hasClass('selected') || downVoteId.hasClass('selected')) {
//user wants to switch votes
$.post('vote.php', {pid: pid, uid: uid, type: type, vote: 'switch'}, function(data) {
var votes = $('#' + voteId);
var num = votes.text();
if (data == '1') {
//downvote successful
votes.text(parseInt(num) - 2);
vote.addClass('selected');
upVoteId.removeClass('selected');
}
if (data == '0') {
//upvote successful
votes.text(parseInt(num) + 2);
vote.addClass('selected');
downVoteId.removeClass('selected');
}
if (d == 'error') {
alert('error');
}
});
} else {
$.post('test2.php', {type: type, pid: pid, uid: uid}, function(d) {
if (d == "1") {
//everything good
$('#' + type + '-<?php echo $pid; ?>').addClass('selected');
var votes = $("#" + voteId).text();
if (type == 'down') {
//downvote
votes = --votes;
$('#' + voteId).text(votes);
} else {
votes = ++votes;
$('#' + voteId).text(votes);
}
} else {
alert('failed');
}
});
}
}
}
}
Vote.php
<?php
session_start();
require('db.php');
if (!isset($_SESSION['id'], $_SESSION['un'])) {
//not logged in
header('Location: index.php');
exit;
} else {
if (!isset($_POST['uid'], $_POST['pid'], $_POST['type'], $_POST['vote'])) {
//form not submitted
header('Location: home.php');
exit;
} else {
$uid = (int)$_SESSION['id'];
$pid = (int)$_POST['pid'];
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$vote = preg_replace('#[^a-z]#', '',$_POST['vote']); //vote type
if ($vote == 'reset') {
//initiate vote reset
if ($type == 'down') {
//downvote
$sql = mysqli_query($con, "DELETE FROM likes WHERE like_type = '1' AND pid = '$pid' AND uid = '$uid'"); //delete the downvote
$sql2 = mysqli_query($con, "UPDATE posts SET likes = likes + 1 WHERE pid = '$pid'");
if ($sql) {
echo "1"; // 1
exit;
} else {
echo "error";
exit;
}
} else {
//upvote
$sql = mysqli_query($con, "DELETE FROM likes WHERE like_type = '0' AND pid = '$pid' AND uid = '$uid'"); //delete upvote
$sql2 = mysqli_query($con, "UPDATE posts SET likes = likes - 1 WHERE pid = '$pid'");
if ($sql) {
echo "0"; // 0
exit;
} else {
echo "error";
exit;
}
}
}
if ($vote == 'switch') {
//user wanted to switch vote
if ($type == 'down') {
//user had voted up but wants to vote down now
$sql = mysqli_query($con, "DELETE FROM likes WHERE like_type = '0' AND pid = '$pid' AND uid = '$uid'"); //delete the previous vote
$sql2 = mysqli_query($con, "INSERT INTO likes (pid, uid, like_type, date_liked) VALUES ('$pid', '$uid', '1', now())"); //insert new vote
$sql3 = mysqli_query($con, "UPDATE posts SET likes = likes - 2 WHERE pid = '$pid'");
if ($sql AND $sql2 AND $sql3) {
//all three queries were successful
echo "1";
exit;
} else {
echo "error";
exit;
}
} else {
//user had voted down but wants to vote up now
$sql = mysqli_query($con, "DELETE FROM likes WHERE like_type = '1' AND pid = '$pid' AND uid = '$uid'") or die(mysqli_error($con)); //delete the previous vote
$sql2 = mysqli_query($con, "INSERT INTO likes (pid, uid, like_type, date_liked) VALUES ('$pid', '$uid', '0', now())"); //insert new vote
$sql3 = mysqli_query($con, "UPDATE posts SET likes = likes + 2 WHERE pid = '$pid'");
if ($sql AND $sql2 AND $sql3) {
//all three queries were successful
echo "0";
exit;
} else {
echo "error";
exit;
}
}
}
}
}
Test2.php
<?php
require('db.php');
$pid = $_POST['pid'];
$uid = $_POST['uid'];
$type = $_POST['type'];
if ($type == "down") {
//downvote
$type = 1;
$sql = mysqli_query($con, "INSERT INTO likes (uid, pid, like_type, date_liked) VALUES ('$uid', '$pid', '$type', now())");
$sql2 = mysqli_query($con, "UPDATE posts SET likes = likes - 1 WHERE pid = '$pid'");
if ($sql) {
echo '1';
exit;
}
} else {
//upvote
$type = 0;
$sql = mysqli_query($con, "INSERT INTO likes (uid, pid, like_type, date_liked) VALUES ('$uid', '$pid', '$type', now())");
$sql2 = mysqli_query($con, "UPDATE posts SET likes = likes + 1 WHERE pid = '$pid'");
if ($sql) {
echo '1';
exit;
}
}
These are my pages that are currently used. I plan on moving test2.php to vote.php.
In my database I have two tables, one to store all the post details including the number of votes. The second table is to store who voted for what post and if it was an upvote or down.
If I could make my system more efficient, please give me tips or recommendations.
Quick SQL hack: make a unique index on pid,uid so that a user can only ever vote once on a post.
ex: ALTER TABLE vote ADD UNIQUE INDEX pid_uid (pid, uid);
Quick JS hack: set a variable on submit that you don't clear until the response; if the variable is set, you don't submit the form. Thus, spam clicking will do nothing, since every click after the first will be ignored.
ex:
var submitting = false;
function submit_form()
{
if (!submitting)
{
submitting = true;
// example; insert actual arguments for it to work
$.post(
url,
postData,
function (data, textStatus)
{
submitting = false;
// handle data here
},
"json"
);
}
}
Well, there is a lot of improvement to be done.
First you are running open to SQL injection queries. Move that to prepared statement.
Then you can, before insert, check if user already voted for that type, as you already have uid, pid, and like_type. This is server-side.
Client-side your JavaScript could disable clicked button to prevent double click. This will prevent user's to send many requests to the server.
The goal here is let server, PHP, handle the verification if the user already voted to that post, as client -ide is easily manipulated in this case.
Don't forget, move those SQL queries to something safe.
Ultimately, you can only hope to control multiple voting using server-side validation.
Stack Overflow requires the user to sign in to a known account in order to vote, which makes it more difficult (but of course not impossible) for multiple votes.
If you do not require that, the best solution depends on your specific requirements.
A simple, client-only solution is to set a cookie indicating the user has voted. Disable the appropriate UI element if that cookie is set. Someone who clears cookies or uses InPrivate style browsing will easily bypass that. Someone can also write their own client that ignores the cookie. Perhaps it is sufficient for your requirements.
A naive server-side solution is to allow only one vote per IP address. I do not recommend this, but include it so you understand why. Unfortunately, a single user can have multiple IP addresses (just drive down the road on your mobile device and see how many IPs you get), or a single IP can represent multiple physical computers (proxy server).
A solid server-side solution would combine the IP address, user agent, and various aspects of the device to yield a device fingerprint. This is a complex solution, beyond the needs of most websites (but if you need it, there are a few companies out there that offer device fingerprinting). Check out https://panopticlick.eff.org/
Summary
If you can require the user to log in to vote (like StackOverflow), that will often be the best solution.
If you cannot require that, use device fingerprinting if it is in your budget, otherwise rely on a cookie. If you do the latter, it may still be worth logging the IP address and user agent of voters so that you can keep an eye out for blatant cheating.
I'd consider storing a voter's IP address in a mysql table as an INT once they have voted.
After that either just show them the tally, or provide them the option to undo their vote by voting up/down.
Check out the PHP function ip2long:
http://www.php.net/manual/en/function.ip2long.php
Use that to convert the IP address into INT format and store it in your mysql to reference against.
Other Resources:
http://www.php.net/manual/en/function.long2ip.php
http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton

want to get to another page while i m under an ajax call

helllo i m making a quiz. i m fetching questions from database . while im using ajax to display the questions by refreshing a div tag. here is the code of ajax used.
$(document).ready(function(){
$("#button").click(function(){
var q_id=$("#h_val").val();
$("#rv").val(q_id);
$.ajax({ url: 'data.php',
type: "POST",
data: {"q_id":q_id} ,
success: function(result) {
$('#que').html(result);
var newValue = parseInt(q_id) + 1
$('#h_val').val(newValue);
}
});
});
});
now this is the data.php page code.
<?php
$qid=$_POST['q_id'];
$con = mysql_connect('localhost', 'root', '') or die(mysql_error());
$db = mysql_select_db('quiz', $con) or die(mysql_error());
$q="select * from question where qno=$qid";
$rq=mysql_query($q,$con);
if(!$rq)
{
echo " the sql query faiiled to work ";
}
else
{
if (mysql_num_rows($rq) == 0)
{
echo "database is empty.";
}
else
{
while ($sub_row=mysql_fetch_array($rq))
{
$id=$sub_row["qno"];
$question=$sub_row["question"];
$option1=$sub_row["option1"];
$option2=$sub_row["option2"];
$option3=$sub_row["option3"];
$option4=$sub_row["option4"];
echo "<h5>Q".$id." : ".$question."</br></h5>";
echo"</br><br>
<h4><input type= radio id='1' name=\"{$id}\" value=\"{$option1}\">$option1</h4>
</br>
<h4><input type= radio id='2' name=\"{$id}\" value=\"{$option2}\">$option2</h4>
</br>
<h4><input type= radio id='3' name=\"{$id}\" value=\"{$option3}\">$option3</h4>
</br>
<h4><input type= radio id='4' name=\"{$id}\" value=\"{$option4}\">$option4</h4>
</br></br>";
}
}
}
?>
i just want to go to a page when the question get over. while using header loaction whole page is coming in div . i just want a code to replace the line "databse is empty" which will redirect me to anther page .
Should be done in js. As per your current code, try this
success: function(result) {
if(result=="database is empty.") {
window.location="newurl.php";
}
$('#que').html(result);
var newValue = parseInt(q_id) + 1
$('#h_val').val(newValue);
}

Categories

Resources