I am trying to create a very basic auction page on a site I am working on. I'm sort of working it out as I go along but I am now a bit stuck.
Data is stored in a MySQL table, this data has the image link, the ID, and the current bid.
I then retrieve the data in PHP/HTML, example here:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction'><div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £" . $row['CurrentBid'] . "</div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid'/></div>";
echo "<div class='auction-bid'><button name='submit' id='submit' value='" . $row['ID'] . "' type='submit'>Place Bid!</button></div>";
echo "</div></form>";
}
echo "</table>";
This code pulls through the items absolutely fine. Along with a textbox for a name and a bid (I am not doing anything with the name at the moment).
My jQuery then looks like this:
$(document).ready(function(){
$('#auction').submit(function(){
var id = $('#submit').val();
var bidname = $('input[name=bidname]').val();
var bid = $('input[name=bid]').val();
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
success: function(){
}
});
return true;
});
});
Again this is very basic and I am not concerned about validation just yet.
And finally here is a snippet of my PHP code:
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$query = "UPDATE auction SET CurrentBid = '$bid' WHERE ID = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
My problem is that when I click submit, nothing really happens. All the variable names and values get put into the browser address bar, and the page just seems to refresh.
The data does not get posted and when I debug with Firebug, I just get a red cross and it doesn't give me any errors.
I know from just looking at my code that best practices aren't followed, but I just want to get something working and then tidy it up later.
If anyone could point me in the right direction that would be a big help.
Thank you, and if you need anymore information please just let me know.
First of all: You need to rewrite your form element every element should have an unique id to differentiate the respective element.
<?php while($row = mysqli_fetch_array($result)){ ?>
<form name='auction' id='auction<?php echo $row['ID'] ?>'>
<input type='hidden' name='id' value='<?php echo $row['ID'] ?>'>
<div class='auction-thumb'>
<div class='auction-name'><?php echo $row['Item'] ?></div>
<img class='auction' src='<?php echo $row['ImagePath'] ?>' />
<div class='auction-bid'>Current Bid: £<?php echo row['CurrentBid'] ?></div>
<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname'/></div>
<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid'/></div>
<div class='auction-bid'>
<input type='submit' name='submit' value='Place Bid!'>
</div>
</div>
</form>
and replace your jquery code to
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).('input[name="bid"]').val();
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
success: function(){
}
});
return false;
});
});
You need to re-write this a bit: ID's have to be unique and when you loop through your items you assign the same IDs over and over to elements in different forms.
So when you try to get the values in your submit handler, jQuery does not know which value to get (it probably gets the value of the first element with that ID).
You should start with changing the IDs to for example classes and then serialize (for example...) the submitted form - $(this) in your submit handler - to get the correct data.
Add following keys in ajax to trace the errors.
$.ajax({
url: "auction-handler.php",
type: "POST",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
crossDomain:true,
success: function(result){ console.log(result); }
error: function(httpReq,status,exception){
alert("error - " +status+" "+exception);
}
});
Related
I've a button inside a form:
echo '<tr class="user-personal-info">';
echo "<td><p>".$row['user_id']."</p></td>";
echo "<td><input placeholder='Username' type='text' value='".$row['user_name']."'/></td>";
echo "<td><input placeholder='Email' type='email' value='".$row['user_email']."'/></td>";
if($row['user_status'] == 1) {
echo "<td><select>";
echo "<option>User</option>";
echo "<option>Admin</option>";
echo "</select></td>";
} else {
echo "<td><select>";
echo "<option>Admin</option>";
echo "<option>User</option>";
echo "</select></td>";
}
echo "<td><input id='delete_btn' onclick='deleteUser(this);' type='submit' value='Delete'/></td>";
echo '</tr>';
As you can see there is a click event on the button. When i hit the button the following javascript function is executed. ID containes the id of a specific row ($row['user_id']):
function deleteUser(deze) {
const ID = deze.parentNode.parentNode.children[0].innerText
$.ajax({
url: "./includes/delete_user.php",
method: "POST",
data: {id:ID},
success: function(data) {
alert(data);
}
});
}
I want to send this ID variable to PHP to delete that specific record that matches with the ID. The problem is that my ID from JS is not send to PHP. When i echo this in PHP i get following error: Notice: Undefined index: id in....
PHP code:
<?php
include_once('./conn.php');
session_start();
$id = $_POST['id'];
echo $id; //can't echo this variable sent from javascript...
?>
You've put your submit button in a <form>, so after the JavaScript runs (but before the Ajax response is back and you alert it) the browser navigates to a new page (killing the JS program that is waiting for the response).
It is the new page that is showing the error and not the Ajax response.
Don't use type="submit" if you don't want to submit a form.
Use type="button".
I'm learning PHP and SQL and as exercise I'm working on a page that is actually something like admin panel for a website that lists movies. I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.
Because I'm beginner and my code is probably messy, I'm describing what I tried to achieve. There's login.php page where the only functionality is typing username and password. If info matches info from SQL table, user proceeds to adminpanel.php.
This page should load a list of movies and create a table with that data. At the end of each row I want two buttons, edit and delete. What I'm trying to achieve is to delete current row where delete button is clicked, for delete button. Edit button should show hidden form just for the row where button was clicked. This form would contain button that actually updates data in SQL table after filling form and clicking the button. (I haven't added function that shows form yet, I care about buttons much more) Form for adding movies at the end of the file works.
Here's adminpanel.php
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript" src="changes.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>
<style type="text/css">
*{text-align: center;}
.skriveni_input{
display: none;
};
</style>
</head>
<?php
require_once('connection.php');
if(!isset($_POST['btnlogin'])){
exit;
}
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT usrname,password FROM usrs WHERE usrname='$username' AND password='$password' ";
$res = mysqli_query($conn,$query);
$rows = mysqli_num_rows($res);
if($rows == 1){
echo "Welcome ".$_POST['username']."<br><br>";
} else {
echo "<script>
alert('Wrong login info');
window.location.href='login.php';
</script>";
exit;
}
$query = "SELECT * FROM movies";
$result = $conn->query($query);
echo "<table align = center cellspacing = 0 border = 0;><thead><tr><th>Name</th><th>Year</th><th>Genre</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo '<td id="row_id" style="display:none;" value="'.$row["movie_id"].'">'.$row["movie_id"].'</td>';
echo '<td>'.$row["name"].'</td>';
echo '<td>'.$row["year"].'</td>';
echo '<td>'.$row["genre"].'</td>';
echo '<td><input type="submit" name="edit" value="edit" data-index="' . $row['movie_id'] . '" class="btnedit" id="btnedit"></input></td>';
echo '<td><input type="submit" name="delete" value="delete" class="btndlt" id="btndlt"></input></td>';
echo "</tr>";
echo "<tr>
<td><input type='text' class='hidden_input' id='hidden_name" . $row['movie_id'] . "'placeholder='hidden name'></input></td>
<td><input type='text' class='hidden_input' id='hidden_year" . $row['movie_id'] . "'placeholder='hidden year'></input></td>
<td><input type='text' class='hidden_input' id='hidden_genre" . $row['movie_id'] . "'placeholder='hidden genre'></input></td>
</tr>";
}
echo "</tbody></table>";
?>
<h3>Add movie form: </h3>
<form action="" method="POST">
<label for="movie_name">Movie name : </label>
<input type="text" name="movie_name" id="movie_name">
<br><br>
<label for="movie_year">Year: </label>
<input type="text" name="movie_year" id="movie_year">
<br><br>
<label for="movie_genre">Genre: </label>
<input type="text" name="movie_genre" id="movie_genre">
<br><br>
<input type="submit" name="submit_movie" id="submit_movie" value="Submit">
</form>
</html>
Here's my javascript file with ajax calls:
$(document).ready(function(e){
$('#submit_movie').click(function(e){
e.preventDefault();
var movie_name = $('#movie_name').val();
var movie_year = $('#movie_year').val();
var movie_genre = $('#movie_genre').val();
$.ajax({
type: 'POST',
data: {movie_name:movie_name, movie_year:movie_year, movie_genre:movie_genre},
url: "insert.php",
success: function(result){
alert('Movie ' + movie_name + ' (' + movie_year + ')' +' added successfully.');
document.location.reload();
}
})
});
$('.btnedit').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().html();
alert(id);
//unfinished function
})
$('.btndlt').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().prev().html();
e.preventDefault();
$.ajax({
type: 'POST',
data: {id:id},
url: 'delete_row.php',
success: function(result){
alert('Successfully deleted.');
document.location.reload();
}
})
})
});
Here's php page for adding a movie, insert.php (this one works, posting it just for more information) :
<?php
require_once('connection.php');
if($_REQUEST['movie_name']){
$name = $_REQUEST['movie_name'];
$year = $_REQUEST['movie_year'];
$genre = $_REQUEST['movie_genre'];
$sql = "INSERT INTO movies(name, year, genre) VALUES ('$name','$year','$genre')";
$query = mysqli_query($conn, $sql);
}
?>
Here's delete_row.php file for deleting entry with delete button:
<?php
require_once('connection.php');
$id = $_REQUEST['id'];
if(isset($_REQUEST['delete'])){
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
As you can probably see I was all over the place with php and ajax because I tried to implement multiple solutions or mix them to solve the problem.
At this stage when I click delete button I get alert message that says erasing is successful and adminpanel.php reloads with list of movies. However the movie is still there and in SQL database.
When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.
Edit
I should've said that security is not my concern right now, I do this exercise just for functionalities I described. :) Security is my next step, I am aware this code is not secure at all.
When I tried to debug delete_row.php I found out that index "id" is
undefined every time even though I think I'm passing it with ajax
call.
The reason this happens is probably because you're accessing delete_row.php directly through the browser, and because the form is not submitted (it will later through ajax) the $_REQUEST variable will always be undefined.
When debugging $_REQUEST (or $_POST) variables in the future, you should use Postman where you can actually request that php file sending your own POST arguments.
On your specific code, the query will never run because of this line:
if(isset($_REQUEST['delete']))
Which is checking for a delete variable that was never sent in the first place, hence will always resolve false
Use this code instead on delete_row.php:
<?php
require_once('connection.php');
if(isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
So i wanted to make a little "search engine" for my database.
my javascript is:
$(document).ready(function () {
$("#display").click(function () {
var zoeknaam = $("#zoeknaam").val();
var zoektype = $("#zoektype").text();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "display.php",
data: { name: zoeknaam, zoekt: "name" },
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
my html is the following:
<input type="text" name="inputtext" id="zoeknaam" />
<select name="searchtype" id="zoektype"><option value="name">name</option><option value="age">age</option></select>
<input type="button" id="display" value="Display All Data" />
and now i have my php
include("connection.php");
$dataget = $_POST["name"];
$datawaar = $_POST["zoekt"];
$stmt = $conn->prepare("SELECT * FROM student WHERE :waar=:postname");
$stmt->bindParam(':waar', $datawaar, PDO::PARAM_STR);
$stmt->bindParam(':postname', $dataget, PDO::PARAM_STR);
$stmt->execute();
echo "<table>";
while($data = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td align=center>$data[name]</td>";
echo "<td align=center>$data[address]</td>";
echo "<td align=center>$data[age]</td>";
echo "</tr>";
}
echo "</table>";
When i remove the where condition and set the condition to name it works. Now when i retrieve it with the post and param it doesn't work.
The connection.php is correct since it works with the condition.
This is wrong:
... WHERE :waar=:postname
You can only bind values using placeholders in a prepared statement, not column- or table names.
If you want to accept and use client-provided column- or table names, the only way to secure that, is to check them against a white-list and then inject them directly in the query string.
I am creating a basic auction site and having a slight issue where when a bid is placed, it sometimes says it's too low, despite it being higher than the current bid. I think this is to do with the way I am getting the current bid, as it's not a very tidy approach in my opinion.
So my HTML/PHP which retrieves and lists the auctions on the page:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction" . $row['ID'] . "'>
<input type='hidden' name='id' value='" . $row['ID'] . "' />
<div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
echo "<div class='bid-success' id='bid" . $row['ID'] . "'>Bid placed!</div>";
echo "</div></form>";
As you can see, I wrap the column/value "CurrentBid" in a div with the ID of the ID in MySQL.
Then when someone places a bid, the following jQuery/AJAX code is called:
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).find('input[name="bid"]').val();
var currentbid = $('#'+id).text();
var itemdesc = $(this).find('.auction-name').text();
if (bidname == '')
{
alert("No name!")
return false;
}
if (bid > currentbid)
{
alert("Bid is greater than current bid");
}
else
{
alert("Bid is too low!");
return false;
}
$.ajax({
type: "POST",
url: "auction-handler.php",
data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
success: function(data){
$('#bid'+id).fadeIn('slow', function () {
$(this).delay(1500).fadeOut('slow');
});
}
});
return false;
});
});
As you can see from this code, I assign the variable 'currentbid' by selecting the ID of the div container, and then pulling through the text within it.
I am not sure if this is what is causing me the problem, but it seems likely, I cannot figure out why sometimes it says "Bid too low" despite me putting in a higher price then what is currently in the Current Bid div.
Ideally, I'd like to assign the jQuery variable 'currentbid' with the value directly from MySQL, but I am not too sure if this is possible.
Does anyone know of a way that I can do this? Or is there a better way I can assign a value to the variable?
Thank you
You are comparing strings now instead of numeric values. You should cast your values to floats before comparing.
bid = parseFloat(bid)
currentbid = parseFloat(currentbid);
Also on the server side when processing to bid you should first check the currentBid from the database because it could have changed already.
Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}