AJAX wont do what I want
Can you find the problem? It doesnt insert it into the database but I get no error.
Im a total ajax noob yes, I found this code and modified it a bit and i think it should work but it dont
rate.php
$v = $_GET['v'];
$conn = mysql_connect('***', '***', '***');
$db_selected = mysql_select_db('***', $conn);
$sql="INSERT INTO votes (title_id, score) VALUES (1, $v)";
$result = mysql_query($sql) or die(mysql_error());
echo "Vote has been added.";
?>
title.php
<script type="text/javascript">
function addVote(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","include/ajax/rate.php?v="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
Rate: <a href="#" onclick="addVote(1)">1</a> <a href="#" onclick="addVote(2)"&开发者_开发知识库gt;2</a> <a href="#" onclick="addVote(3)">3</a> <a href="#" onclick="addVote(4)">4</a> <a href="#" onclick="addVote(5)">5</a>
Can't see anything wrong (as far as logic is concerned). So here is a vague debug answer:
First you should simply call your php script directly to see if and what it outputs:
http://localhost/thingy/include/ajax/rate.php?v=3
If that works, then the problem is your Javascript code. Try with jQuery just to be sure:
function addVote(n) {
$('#txtHint').load("rate.php?v=" + n);
}
Add a timestamp to avoid caching:
xmlhttp.open("GET","include/ajax/rate.php?t="+new Date().getTime()+"&v="+str,true);
validation of the input:
$v = filter_input(INPUT_GET,
'v',
FILTER_VALIDATE_INT,
array(
'flags' => FILTER_NULL_ON_FAILURE,
'options' => array('min_range' => 1, 'max_range' => 5)
));
if(!$v){exit();}
Try put single quote in the query string's values:
$sql="INSERT INTO votes (title_id, score) VALUES ('1', '" . mysql_real_escape_string ($v) . "')";
and use
mysql_real_escape_string (string $unescaped_string [, resource $link_identifier ]);
on the variable to inject
精彩评论