Rating script wont update when multiple rate - javascript

Hi i am currently making a rating script and i have a few problems
Right now the script "kinda" works -> http://xch07.wi2.sde.dk/sandbox/rating2/index.php
The problem is that if i open up 2 browsers and load image 1 on both browsers and rate the image on both the browsers the last query sent will override anything inbetween so basically in the end only 1 vote out of the 2 is submitted?.
Right now my db looks like this:
id - votes - rating
Currently i just increment the votes with 1 when a vote is submitted
And i raise the raiting with whatever value has ben voted
Could someone tell what i have to do to overcove this problem? and any other thoughs on my code are greatly appreciated :)
OBS: Does anyone have an idea of how i can check if a person has already voted a given image?
HTML
<div class="flex">
<div class="imageWrapper mauto relative fadeInClass">
<img id="imgSrc" src="assets/img/<?php echo $id ?>.png" class="carImg">
<input id="imgValue" class="absolute displayn" type="radio" value="<?php echo $id ?>">
<input id="imgVotes" class="absolute displayn" type="radio" value="<?php echo $votes ?>">
<input id="imgRating" class="absolute displayn" type="radio" value="<?php echo $rating ?>">
<form action="" method="post" class="flex flex-drr absolute bot0 left0">
<input id="vote5" class="vote displayn" type="radio" name="vote" value="5">
<label for="vote5"></label>
<input id="vote4" class="vote displayn" type="radio" name="vote" value="4">
<label for="vote4"></label>
<input id="vote3" class="vote displayn" type="radio" name="vote" value="3">
<label for="vote3"></label>
<input id="vote2" class="vote displayn" type="radio" name="vote" value="2">
<label for="vote2"></label>
<input id="vote1" class="vote displayn" type="radio" name="vote" value="1">
<label for="vote1"></label>
<input type="submit" id="voteSubmit" class="displayn">
</form>
</div>
</div>
Javascript/Ajax
var vote = document.getElementsByClassName('vote');
var voteL = vote.length;
for (let i = 0; i < voteL; i++) {
vote[i].addEventListener('click', function () {
let imgValue = document.getElementById("imgValue");
let imgVotes = document.getElementById("imgVotes");
let imgRating = document.getElementById("imgRating");
let imgValueVal = imgValue.value;
let imgVotesVal = imgVotes.value;
let imgRatingVal = imgRating.value;
let voteValue = vote[i].value;
newImage(imgValueVal, imgVotesVal, imgRatingVal, voteValue);
});
}
function newImage(id, votes, rating, voteValue) {
var http = new XMLHttpRequest();
var url = "pages/newImage.php";
var params = "id=" + id + "&votes=" + votes + "&rating=" + rating + "&voteValue=" + voteValue;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {//Call a function when the state changes.
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
var Data = JSON.parse(this.responseText);
alert(Data.id);
let imgSrc = document.getElementById('imgSrc');
imgSrc.src = Data.imgSrc;
let imgValue = document.getElementById('imgValue');
imgValue.value = Data.id;
let imgVotes = document.getElementById('imgVotes');
imgVotes.value = Data.votes;
console.log(Data.votes);
let imgRating = document.getElementById('imgRating');
imgRating.value = Data.rating;
}
}
http.send(params);
}
THE PAGE AJAX REQUESTS
<?php
require_once '../includes/db.php';
require_once '../includes/functions.php';
$dbCon = dbCon();
//UPDATERE DATABASED
$id = $_POST['id'];
$votes = $_POST['votes'];
$rating = $_POST['rating'];
$voteValue = $_POST['voteValue'];
$votes++;
$rating = $rating + $voteValue;
$stmt = $dbCon->prepare("UPDATE rating SET
votes = ?,
rating = ? WHERE id = " . $id);
$stmt->bind_param('ii', $votes, $rating);
$stmt->execute();
//SENDER NY QUERY AFSTED
define("SQL", "SELECT * FROM rating ORDER BY rand() LIMIT 1");
$result = $dbCon->query(SQL);
$result = $result->fetch_object();
$id = $result->id;
$votes = $result->votes;
$rating = $result->rating;
$imgSrc = "assets/img/" . $id . ".png";
$arr = array('imgSrc' => $imgSrc, 'id' => $id, 'votes' => $votes, 'rating' => $rating);
echo json_encode($arr);

Why don't you replace the prepared statement with the following:
$stmt = $dbCon->prepare("UPDATE rating SET
votes = ?,
rating = rating + ? WHERE id = " . $id);
Held og lykke :-)

By submitting the current rating/votes to your PHP script, you open yourself up to potentially updating your database based on stale information. You can UPDATE values in the database based on current row values, so the following would work as well:
$stmt = $dbCon->prepare("UPDATE rating SET votes = votes + 1, rating = rating + ? WHERE id = ?");
$stmt->bind_param('ii', $_POST['voteValue'], $_POST['id']);
$stmt->execute();

Just amend your query to add 1 to what is currently in the column like this
$stmt = $dbCon->prepare("UPDATE rating
SET votes = votes + 1,
rating = rating + ?
WHERE id = ?");
$stmt->bind_param('ii', $_POST['voteValue'], $_POST['id']);

Related

Default Radio button value from Database

I have the following code which works great to store the value of the radio button and write to the database(HTML--> Javascript --> PHP).
Now i have a update modal and want to populate the radio button values of a previous record. I am not sure what i am doing wrong, but i can't get the default values for the radio button to show when the user hits update.
HTML
<div class="form-group">
<label for="update_flag">Update Flag:</label>
<br>
<label class="radio-inline"><input type="radio" name="update_flag" value="Yes">Yes</label>
<label class="radio-inline"><input type="radio" name="update_flag" value="Maybe">Maybe</label>
<label class="radio-inline"><input type="radio" name="update_flag" value="No">No</label>
</div>
Javascript: The JSON.Parse returns a YES/NO/MAYBE and i've checked that it is returning it properly.
function GetUserDetails(id) {
$("#hidden_user_id").val(id);
$.post("ajax/readUserDetails.php", {
id: id
},
function (data, status) {
// PARSE json data
var va = JSON.parse(data);
$("output[name=update_flag]:checked").val(va.flag);
}
);
// Open modal popup
$("#update_user_modal").modal("show");}
PHP:
<?php
// include Database connection file
include("db_connection.php");
// check request
if(isset($_POST['id']) && isset($_POST['id']) != "")
{
// get ID
$id = $_POST['id'];
// Get Details
$query = "SELECT flag,
FROM list WHERE id = '$id'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
$response = array();
if(mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$response = $row;
}
}
else
{
$response['status'] = 200;
$response['message'] = "Data not found!";
}
// display JSON data
echo json_encode($response);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid Request!";
}
I think $("output[name=update_flag]:checked").val(va.flag); is where it went wrong. You should try something like this:
$("input[name=update_flag][value=" + radioBtnValueToCheck + "]").prop('checked', true);

Trying to Prepare a Statement To Store In Database

Ok. I have a form with two input fields. One is to capture the date, the other is a text field for the "goal title". I have button to click to add another "goal title" field when pressed. On form submission, there will be anywhere between 2 and 21 entries.
(There will be one single date entry that will apply to all "goal titles" and as many as 20 "goal titles".
The html for the form looks like this:
<form action="handlers/add-goals.php" method="POST">
<h1>Add Goals</h1>
<input type="hidden" name="assigned_by_user_id" value="<?php echo $user_id; ?>">
<input type="hidden" name="assign_to_user_id" value="<?php echo $user_id; ?>">
<div class="form-group">
<label>What Date Are You Adding Goals For?</label>
<input class="form-control datepicker" type="text" name="due_date" required>
</div>
<div class="form-group">
<label>Goal #1:</label>
<input class="form-control" type="text" name="goal_title" required>
</div>
<div id="dynamicInput"></div>
<div class="form-group">
<input class="form-control btn btn-default" type="button" value="Add Another Goal Area" onClick="addInput('dynamicInput');">
</div>
<input type="submit" class="btn btn-primary" name="submit" value="Add Goal(s)">
</form>
Then we have the javascript that looks like this:
var counter = 1;
var limit = 20;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='form-group'><label>Goal # " + (counter + 1) + "</label><input class='form-control' type='text' name='goal_title' required></div>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Finally, the PHP form that it is submitting to is:
<?php
include('../../includes/db_con.php');
$due_date = $_POST['due_date'];
$date_assigned = date("Y-m-d");
$goal_titles = $_POST['goal_title'];
if($due_date<$date_assigned) {
echo '<script> alert("Sorry. You can not make a goal due before today\'s date!"); </script>';
echo '<script> window.location.href="../add-goal.php"; </script>';
}
else {
$stmt = $con->prepare("INSERT INTO goals (title, instructions, belongs_to, assigned_by, due_date, date_assigned, completed, completed_on, deleted, notes) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") or die("Error: " . $con);
for ($i=0; $i<count($goal_titles); $i++) {
$title = $goal_titles[$i];
$instructions = '';
$assigned_by_user_id = $_POST['assigned_by_user_id'];
$assigned_to_user_id = $_POST['assign_to_user_id'];
$due_date = $_POST['due_date'];
$date_assigned = date("Y-m-d");
$completed = 'NO';
$completed_on = '';
$deleted = '0';
$notes = '';
$stmt->bind_param('ssssssssss', $title, $instructions, $assigned_to_user_id, $assigned_by_user_id, $due_date, $date_assigned, $completed, $completed_on, $deleted, $notes);
$stmt->execute();
}
$stmt->close();
echo '<script> alert("Added to your goals!"); </script>';
echo '<script> window.location.href="../add-goal.php"; </script>';
}
?>
What I am experiencing is the php script is storing the last "goal_title" row to the database instead of all of them and it is only capturing the first letter of that "goal_title".
I'm assuming my error is in the php script but included everything so you can see all that is going on.
To elaborate on my comment, you need to send an array of goal_title data. You tell PHP that the data is an array by adding square brackets to the form element name attribute. For example
<div class="form-group">
<label>Goal #1:</label>
<input class="form-control" type="text" name="goal_title[]" required>
</div>
and in your JS
...<input class='form-control' type='text' name='goal_title[]' required>...
An extra thing to note is that statements only need to be prepared and bound once. The variables used in bind_param are passed by reference so their values may be changed.
$stmt = $con->prepare("INSERT INTO goals (title, instructions, belongs_to, assigned_by, due_date, date_assigned, completed, completed_on, deleted, notes) values (?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?)");
$instructions = '';
$assigned_by_user_id = $_POST['assigned_by_user_id'];
$assigned_to_user_id = $_POST['assign_to_user_id'];
$due_date = $_POST['due_date'];
$completed = 'NO';
$completed_on = '';
$deleted = '0';
$notes = '';
// note that $title may be unassigned at this point
$stmt->bind_param('sssssssss', $title, $instructions, $assigned_to_user_id, $assigned_by_user_id, $due_date, $completed, $completed_on, $deleted, $notes);
foreach($goal_titles as $title) {
$stmt->execute();
}

Store different value in the database from the forms created dynamically using PHP?

Have a look at the screenshot below.
As per the screenshot, I have the data fetched into the different blocks based on the database. For example, based on the username and password, these values are fetched from the database and displayed in different blocks. I have the PHP to store the value into the database, but the problem that I am facing is that when i try to upload it from other block, it still saves the value from the first block.
Codes as as below:
<?php
include('includes/config.php');
$upload = 'uploads/';
session_start();
$_SESSION['$userid'];
$sql = "SELECT * FROM tbl_store INNER JOIN tbl_job ON tbl_store.store_code = tbl_job.store_code WHERE username = '$userid'";
$result = mysqli_query($conn,$sql);
$rowcount=mysqli_num_rows($result);
// echo "$rowcount";
$stores = array();
$stores_add = array();
$stores_chain = array();
$job = array();
$client = array();
$brand = array();
$week= array();
$x = 1;
$imgCnt =1;
while($row = mysqli_fetch_array($result)){
echo "工作".'<br/>';
echo $row['jobs'].'<br/>'.'<br/>';
$job[] = $row['jobs'];
echo "客戶".'<br/>';
echo $row['Client'].'<br/>'.'<br/>';
$client[] = $row['Client'];
echo "牌子".'<br/>';
echo $row['Brand'].'<br/>'.'<br/>';
$brand[] = $row['jobs'];
echo "週數".'<br/>';
echo $row['week'].'<br/>'.'<br/>';
$week[] = $row['week'];
$target = $upload.'/'.$row['Client'].'/'.$row['Brand'].'/'.$row['jobs'].'/'.$row['store_code'].'/';
$testpath = $row['Client'].'/'.$row['Brand'].'/'.$row['jobs'].'/'.$row['store_code'].'/';
$_SESSION['target1'.$x] = $target;
if(!file_exists($target))
{
mkdir($target,0777,true);
}
?>
<form id='uploadForm-<?php echo $imgCnt; ?>' action = '' enctype='multipart/form-data' method = 'POST' class="form<?php echo $imgCnt; ?>">
<input type="file" class="image<?php echo $imgCnt; ?>" name="img" onChange="readURL(this);" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type='button' id = '<?php echo $imgCnt; ?>' class='uploadPicture<?php echo $imgCnt; ?> btn btn-primary' value = '上載'>
<!-- <input type="button" value="上載" class="uploadPicture" id="upload_btn<?php echo $imgCnt; ?>"/> -->
</form>
<form enctype="application/x-www-form-urlencoded">
<table width="200" border="1">
<tr>
<td>Product</td>
<td>Promotional Price</td>
<td>Regular Price</td>
<td>Stacking</td>
</tr>
<tr>
<td><input type="text" id="product"></td>
<td><input type="text" id="pp1"></td>
<td><input type="text" id="rp1"></td>
<td><input type="text" id="stacking"></td>
</tr>
</table>
<div id ="div1">
<input type="button" value="Submit" onClick="PostData();"/><br/>
</div>
</form>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function PostData() {
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var product = document.getElementById("product").value;
var pp1 = document.getElementById("pp1").value;
var rp1 = document.getElementById("rp1").value;
var stacking = document.getElementById("stacking").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'report.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("product=" + product + "&pp1=" + pp1 + "&rp1=" + rp1 + "&stacking=" + stacking);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
</script>
<?php
echo "-------------------------------------------------------".'<br/>';
$x = $x+1;
$imgCnt++;
}
?>
I have removed the code for image upload from it as it works completely fine. The problem is the data from the other block is not stored to the database. only the value for the first block is stored second time even. How to solve this problem.
PHP to store data:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testing";
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tbl_report (product,pp1, rp1,stacking)
VALUES ('$product', '$pp1', '$rp1','$stacking')";
if ($conn->query($sql) === TRUE) {
echo "Successful";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
To expand on what #Logan Wayne pointed out...
An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code.
So, in your JavaScript, when you grab references to your table data elements, you'll always get the FIRST instance of a Document object with whatever id you provide.
// 2. Define what to do when XHR feed you the response from the server - Start
var product = document.getElementById("product").value; <-- will always return the same element
var pp1 = document.getElementById("pp1").value; <-- will always return the same element
var rp1 = document.getElementById("rp1").value; <-- will always return the same element
var stacking = document.getElementById("stacking").value; <-- will always return the same element
You'll either have to assign unique ids to your td objects, or, again as #Logan Wayne mentioned, utilize the class property of HTML DOM objects.
Classes can be used to group like elements. After assigning class names to the different columns in your table (Product, Promotional Price, Regular Price, Stacking) you can use getElementsByClassName() to get an array of the td elements.
...
var products = document.getElementsByClassName("product"); <-- array of product td elements
...

I have a faulty Ajax call apparently

I have a project where a user can have his own VirtualDiary online. He/She registers logs in and all that and is brought to a entry page with the date and a text area. The idea is that they will be able to click on two buttons on the top of the page titled NextPage and PreviousPage. These will call a jquery ajax function which will in turn change the value of EntryID + 1 or EntryID -1. This should change the value of pretty much everything on the page. But nothing happens even though the ajax call logs success. I am very new to ajax so I have probably Done something really stupid. Thanks in advance
PHP
<?php
session_start();
//error_reporting(E_ERROR|E_WARNING);
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
$JoinDateQuery = mysql_query("SELECT * FROM users WHERE UID = '".$_SESSION['UID']."' ");
if($JoinDateQuery === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($JoinDateQuery))
{
$JoinDate = $row[4];
}
$TodayDate = date("Y/m/d");
$today = strtotime($TodayDate);
$joinTime = strtotime($JoinDate);
$datediff = $today - $joinTime;
$_SESSION["EntryID"] = floor($datediff/(60*60*24));
$EntryID = $_SESSION["EntryID"];
$_SESSION['EntryDate'] = date('Y-m-d', strtotime($JoinDate. ' + '.$EntryID .'days'));
$EntryDate = $_SESSION['EntryDate'];
$id = $_SESSION["UID"] ;
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$deletion = "DELETE FROM entries WHERE UserID = '".$_SESSION['UID']."' and EntryID = '".$EntryID."' ";
mysql_query($deletion);
$submission = "INSERT INTO `virtualdiary`.`entries` (`Entry`, `UserID`,`EntryID`) VALUES ('". $entry . "', '".$_SESSION['UID']."', '".$EntryID."')";
mysql_query($submission);
}
$ThePost = 'SELECT * FROM entries WHERE UserID = "'. $_SESSION['UID'] .'" and EntryID = "'.$EntryID.'"';
$result = mysql_query($ThePost);
if($result === FALSE) {
die(mysql_error());
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Entry.css"/>
<title>Home</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$('#NextDay').click(function(){
$.ajax({
type: "GET",
url: "Home.php",
data: "$EntryID = $EntryID + 1",
success: console.log("success")
}); //ajax call
});//on click next day
});//document ready</script>
</head>
<body>
<section>
<button id="previousDay" class="day">Previous Day</button>
<button class = "day" id = "date">Joined: <?php echo $JoinDate; ?></br>
Entry Number: <?php echo $EntryID + 1; ?></br>
EntryDate: <?php echo $EntryDate ; ?>
</button>
<button class="day" id = "NextDay">Next Day</button>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="80">
<?php
while($row = mysql_fetch_array($result))
{
echo $row['Entry'];
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="calender" class = "day"><h1>Calender</h1></button>
<button id="LogOut">Log Out</button>
</section>
</body>
</html>
By the way EntryID returns result of 4 (or the default for the user on this day) so its pretty obvious the problem has something to do with the Data: part of the ajax or that I am not using ajax in the right context to achieve what I want.
EDIT: I have just been made aware that $EntryID = $EntryID + 1 has to be defined somewhere but where and I can't just plonk it down somewhere cause that would change the first instance of entry id I think.
First of all, I think you should be making an AJAX "POST" request, not a "GET" request. (Just industry standard, since you're sending a value through to a server).
Second, I'm not sure, where you got the syntax to create a data value for that GET request (really weird) however!, in the ajax call where I edited your code, there should now be the correct way of creating & sending de-serializable data.
EDIT
Forgot to mention, that the values sent from the AJAX, can be retrieved using $_REQUEST['xyx'] or $_POST['xyz'].. If you are using get, you can use $_GET['xyz']
UNTESTED
//error_reporting(E_ERROR|E_WARNING);
mysql_connect("localhost", "root", "") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
$JoinDateQuery = mysql_query("SELECT * FROM users WHERE UID = '" . $_SESSION['UID'] . "' ");
if ($JoinDateQuery === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while ($row = mysql_fetch_array($JoinDateQuery)) {
$JoinDate = $row[4];
}
$TodayDate = date("Y/m/d");
$today = strtotime($TodayDate);
$joinTime = strtotime($JoinDate);
$datediff = $today - $joinTime;
$_SESSION["EntryID"] = floor($datediff / (60 * 60 * 24));
$EntryID = $_POST["EntryID"];
$_SESSION['EntryDate'] = date('Y-m-d', strtotime($JoinDate . ' + ' . $EntryID . 'days'));
$EntryDate = $_SESSION['EntryDate'];
$id = $_SESSION["UID"];
if (isset($_POST["entry"])) {
$entry = $_POST["entry"];
$deletion = "DELETE FROM entries WHERE UserID = '" . $_SESSION['UID'] . "' and EntryID = '" . $EntryID . "' ";
mysql_query($deletion);
$submission = "INSERT INTO `virtualdiary`.`entries` (`Entry`, `UserID`,`EntryID`) VALUES ('" . $entry . "', '" . $_SESSION['UID'] . "', '" . $EntryID . "')";
mysql_query($submission);
}
$ThePost = 'SELECT * FROM entries WHERE UserID = "' . $_SESSION['UID'] . '" and EntryID = "' . $EntryID . '"';
$result = mysql_query($ThePost);
if ($result === FALSE) {
die(mysql_error());
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Entry.css"/>
<title>Home</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
$('#NextDay').click(function () {
$.ajax({
type: "POST",
url: "Home.php",
data: {
EntryID: '1' //not sure (this is quite conditional I guess)
},
success: console.log("success")
}); //ajax call
});//on click next day
});//document ready</script>
</head>
<body>
<section>
<button id="previousDay" class="day">Previous Day</button>
<button class="day" id="date">Joined: <?php echo $JoinDate; ?></br>
Entry Number: <?php echo $EntryID + 1; ?></br>
EntryDate: <?php echo $EntryDate; ?>
</button>
<button class="day" id="NextDay">Next Day</button>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="80">
<?php
while ($row = mysql_fetch_array($result)) {
echo $row['Entry'];
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<a href="Calender.php">
<button id="calender" class="day"><h1>Calender</h1></button>
</a>
<button id="LogOut">Log Out</button>
</section>
</body>
</html>
From http://api.jquery.com/jquery.ajax/
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You're trying to happened "$EntryID = EntryID + 1" to "home.php"
"home.php$EntryID = EntryID + 1" doesn't seem like a correct url ?
You should try with the error callback set if you want more informations on the request status.

Trying to add form data to a database using an Ajax request with PHP

I cant quite get my form to add its data to a local database I have setup.
I have a addproducts.php page:
<?php
$title = "Products";
include("Header.php");
include("PHPvalidate.php");
?>
<script src="AjaxProduct.js"></script>
<article>
<section>
<fieldset><legend><span> Add a product to the database </span> </legend>
<form id ="productsform" method="post" onsubmit="return false;">
<input type="hidden" name="submitted" value="true">
<label> Enter a product name: <input type="text" id="name" name="name"/> </label>
<label> Enter a product quantity: <input type="number" id="quantity" name="quantity"/> </label>
<label> Enter a product description: <input type="text" id="description" name="description"/> </label>
<label> Enter a product price: <input type="text" id="price" name="price"/> </label>
<label> Upload a image of the product: <input name="image" accept="image/jpeg" type="file"></label>
<input id="submit" name="submit" type="button" class="reg" value="Add Product">
<div id="check"></div>
</form>
</fieldset>
</section>
</article>
I then have a ajax fetch request to gather up the data to get ready to be posted to the database:
fetch = function () {
var xhr, name, quantity, description, price, target;
xhr = new XMLHttpRequest();
target = document.getElementById("check");
name = document.getElementById("name").value;
quantity = document.getElementById("quantity").value;
description = document.getElementById("description").value;
price = document.getElementById("price").value;
var vars = "name="+name+"&quantity="+quantity+"&description="+description+"&price="+price;
changeListener = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
target.innerHTML = xhr.responseText;
} else {
target.innerHTML = "<p>Something went wrong.</p>";
}
};
xhr.open("POST", "addSQL.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = changeListener;
xhr.send(vars);
}
pageLoaded = function() {
var fetchbutton = document.getElementById("submit");
if(fetchbutton) {
fetchbutton.addEventListener("click", fetch);
}
}
window.onload = pageLoaded;
And finally an addSQL.php
That send the data to the database:
//Stores all information passed through AJAX into the query
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
//Adds information to database
$query = "INSERT INTO products (name, quantity, description, price) VALUES ('$name','$quantity','$description','$price')";
//Runs the query
$result = $mysqli->query($query) OR die("Failed query $query");
echo $mysqli->error."<p>";
//
?>
When i try to add dummy data into the form and submit nothing happens with no errors or anything so Im not sure where the point of failure is.
Any help would be appreciated.
I think you're missing this:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Edit: also now that I look at it, you're vulnerable to SQL injection and an apostrophe in your data will break the query:
$name = $mysqli->real_escape_string($_POST['name']);
$quantity = $mysqli->real_escape_string($_POST['quantity']);
$description = $mysqli->real_escape_string($_POST['description']);
$price = $mysqli->real_escape_string($_POST['price']);
You add some alert() in your code to find the error.
add alert in the every line when you get a value in variable like alert(vars); after the assign value in vars variable

Categories

Resources