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: 1 2 3 4 5
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
Related
I have a simple (or so I thought) PHP, MYSQL, AXAX system set up to register votes for items on my website. I'm only doing upVotes so there's only one button.
My issue is that when the page loads, the correct number of votes for the item is displayed, but upon the first click of the upVote button, the value does not change. I know I must be missing something, but I have no idea what. It's probably simple... but I just can't figure it out.
Everything connects to the DB just fine. That's why I left all that code out.
Any help is greatly appreciated.
This is the javascript I have:
<script type="text/javascript">
function voteButton(str)
{
if (str=="")
{
document.getElementById("voteUp").innerHTML="";
return;
}
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("voteUp").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","vote?id="+str,true);
xmlhttp.send();
}
</script>
This is the php file used to query the database:
<?php
$id=$_GET["id"];
include("myDatabaseStuff.php");
include("global.php");
$result = mysql_query("UPDATE TABLE SET up_mod = up_mod + 1 WHERE img_id = $id");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = mysql_fetch_array($getUpVoteResult))
{
echo $row['up_mod'];
}
?>
This is the HTML I use on the page to display the values/button:
<div class="span1" style="margin:30px 0 0 10px;">
<button onclick="voteButton('<?php echo $id;?>')" class="btn btn-large" type="button" style="margin-top:5px"><div id="voteUp"><?php echo $votes[0] ?></div><i class="icon-thumbs-up"></i></button>
</div>
Add:
$getUpVoteResult = mysql_query("SELECT up_mod FROM table WHERE img_id = $id") or die ("Invalid query: " . mysql_error());
before the while loop.
You also don't need a while loop, since there's just one row.
After your update, please do the separate SELECT.
I made a search bar, for searching users in my database, and I will share my code below. But one problem is that, if I have 5 users in a table, it shows these 5 users, but if I have 1,000 than it shows all 1,000.
Whatever I tried to limit it, it did not work. Sometimes it completely kills the PHP script.
Does anyone know how to solve that and limit to only 5 results displayed per search query from the code below?
HTML INPUT AND AJAX SCRIPT:
<input id="text" type="text" name="text" onkeyup="showHint(this.value)" autocomplete="off" />
<div id="inner" class="inner"></div>
<script>
function showHint(str) {
if (str.length==0) {
document.getElementById("inner").innerHTML="You haven't search. Please have :D";
return;
}
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("inner").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("REQUEST","searchquery.php?text="+str,true);
xmlhttp.send();
}
</script>
AND searchquery.php:
<?
$text = $_REQUEST['text'];
$text = preg_replace('#[^a-z0-9]#i', '', $text);
function connect($database) {
mysql_connect('localhost','root','');
mysql_select_db($database);
}
connect('developing');
$query = "SELECT * FROM users WHERE first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
$action = mysql_query($query);
$result = mysql_num_rows($action);
if ($result == 0) {
$output = "User does not exist...";
}else{
while ($row = mysql_fetch_array($action)) {
$output .= '<div class="output"><img src="/'.$row['avatar'].'"><a href="#">'.$row['first_name'].' '.$row['last_name'].'</div><br />';
}
}
echo $output;
?>
Can anybody see some solution on how to make that limit?
Use LIMIT in your query:
SELECT *
FROM users
WHERE first_name LIKE '%$text%'
OR last_name LIKE '%$text%
LIMIT 5'
UPDATE... this is the code I've implemented from the tutorial, within chrome dev tools in network i can see in header the variable is being sent and in preview i can see the drop down menu however it is not inserted into the loaded webpage
<script type="text/javascript">
$(document).ready(function() {
$('#selectEvidence').change(function(){
alert($(this).val());
});
});
function evidencesearch(str)
{
if (str=="")
{
document.getElementById("case").innerHTML="";
return;
}
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("case").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","searchfunction.php?variable="+str,true);
xmlhttp.send();
}
</script>
<?php
$variable = $_GET['variable']; //used for second drop down menu
//echo "test test test $variable";
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
echo '<label class="input" for="case" type="input">Specify: </label><select id="case" name="case"><option=value"null"></option>'; //Insert to loaded page
$resource = mysql_query("SELECT $variable FROM `evidence`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row[$variable].'">'.$row[$variable].'</option></select>';//Insert to loaded page
}
}
mysql_close($conn)
?>
I think your problem sticks within POST/GET functions; try to call them synchronously and paste please the w3schools tutorial's link you mentioned. Maybe I can help you then by writing more detailed answer.
Cheers.
For some reason \u009a is being sent to the xmlhttp.responseText and not \u0161, and I'm not sure why. I want š to be displayed in the textbox, but, instead, the single character introducer is being sent instead. Any ideas how I can fix this?
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").value=a.first;
document.getElementById("textbox2").value=a.second;
document.getElementById("textbox3").value=a.third;
document.getElementById("textbox4").value=a.fourth;
document.getElementById("textbox5").value=a.fifth;
document.getElementById("textbox6").value=a.sixth;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
header("Content-type: application/json");
---Placeholder for correct DB login info---
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
$textboxValue5 = $queryResult[4];
$textboxValue6 = $queryResult[5];
echo json_encode(array('first'=>utf8_encode($textboxValue),'second'=>
utf8_encode($textboxValue2),'third'=>utf8_encode($textboxValue3),'fourth'=>
utf8_encode($textboxValue4),'fifth'=>utf8_encode($textboxValue5),'sixth'=>
utf8_encode($textboxValue6)));
?>
Adding in the line $mysql->query("SET CHARACTER SET 'utf8'"); inside loadTextBox.php after connecting to the DB and before the SQL query and removing the lines with utf8_encode fixed it.
I have this code:
$result = mysql_query("SELECT * FROM quote ORDER BY RAND() LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['frase'];
It echo´s a random "frase" every time you query.
What I want to do is avoid having the same result in consecutive queries.
To make myself clear, if in my database I´ve got:
1 a
2 b
3 c
If from echo $row['frase']; I got a the the next result can´t be a.
I hope I made myself clear and if not please comment and I´ll expand!
Thanks in advance!
BTW: sorry to #deceze #zerkms #Dr.Molle because last question was a total mess! No harm ment, just a noob on a spree :)
EDIT:
To answer Jason McCreary I actually call it like this:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Since this last query needs to persist across page refreshes, you need to use a session. Something along these lines:
session_start();
if (empty($_SESSION['lastresult'])) {
$_SESSION['lastresult'] = null;
}
$query = "SELECT * FROM `quote` WHERE `id` != '%s' ORDER BY RAND() LIMIT 1";
$query = sprintf($query, mysql_real_escape_string($_SESSION['lastresult']));
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$_SESSION['lastresult'] = $row['id'];
echo $row['frase'];
You may want to store the last x results in the session and use NOT IN () in your query to avoid every second (third, forth, ...) quote being the same.