I'm making this app to practice asynchronous websites, all it does is show the contents of a database table on the site in table format using jQuery and PHP.
Everything works perfectly, except I wanted to add a button on each < tr > that on click deletes the respective entry on the database, however, I can't seem to get it done. I've got through the documentation of everything I used and just don't see the problem. Here is my code:
HTML:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
The table is created on a separate PHP file that's called by ajax, this is the relevant loop:
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['ID']."</td>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default deleteWaitlist" type="submit" name="' . $places['ID'] . '">X</button>
</td>';
echo "</tr>";
}
All buttons are created with the correct 'name' on the final html (that is an auto_increment number).
jQuery:
$(".deleteWaitlist").click(function(){
console.log("click on .deleteWaitlist");
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
console.log("success" + result);
}
});
});
As I said, kinda new to ajax. correct me if I'm wrong: this calls deleteWaitlist.php and posts a parameter 'id' with value '$(this).attr('name')' which is an auto_increment value on the database and should be diferent for every entry.
deleteWaitlist.php
$sql = "DELETE FROM waitlist WHERE id=" . $_POST[id] . "";
mysqli_query($c,$sql);
It's pretty straightforward, isn't it? Can you help me find the mistake? Maybe something like (int)$_POST[id] somewhere? I could swear I tried that everywhere.
EDIT: Strangely, Im not even getting the console log "click on .deleteWaitlist" when I click the button, as if I weren't even clicking it at all. What can be happening? I also changed the id "deleteWaitlist" for a class, since it seems to be the best practice.
Seems there is multiple delete button in your output html and jQuery matches exactly one element when querying for an ID.
Try use CLASS instead of ID on the delete button.
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['ID']."</td>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default deleteWaitlist" type="submit" name="' . $places['ID'] . '">X</button>
</td>';
echo "</tr>";
}
jQuery:
$(".deleteWaitlist").click(function(){
console.log("click on .deleteWaitlist");
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
console.log("success" + result);
}
});
});
Related
I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});
I have many links which are dynamically created with PHP and now I want to add an onclick event.
while($row = mysqli_fetch_array($xyz)) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . "</a></td>";
echo "</tr>";}
but I want like this:
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . onclick="test()"</a></td>";
echo "</tr>";}
is this possible?
I am not sure if I understood what exactly you are asking but I try to answer you the same:
You can't record a normal JS variable in a page session and then to access to it after the loading of a page.
For this case you can use cookies (that are accessible via server-side too):
// put this code into methods that users suggested you.
document.cookie = "value_selected=something"
and once page is loaded:
var cookies = document.cookie.split(';');
var value_selected = JSON.parse(JSON.stringify(cookies[YOUR_COOKIE].split("=")[0]))
or server side:
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" data-something=htmlentities($_COOKIE['value_selected']) target=\_blank>" . $row['z'] . "</a></td>"; //(example)
Or more simply, pass the value selected through query
?value_selected=something //elaborate the new link in the method users suggested you
and
in server-side, use $['GET'] to obtain all values in query string.
IMHO I think the first choice is simpler than second.
I hope I helped you
Try Like this
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a class='myclick' href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . **onclick="test()"**</a></td>";
echo "</tr>";}
i have added a class to link as myclick
and in jquery
$(document).on('click','.myclick',function(e){
e.preventDefault();
alert('clicked');
});
You can try like this..just a simple way.
<script type="text/javascript">
function test(){
alert('test');
}
</script>
<?php
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href='your link' onclick='test()'></a></td>";
echo "</tr>";
}
?>
I have a problem with my website. I have a list of products that i get from database. These products have Image and Name camps.
Now i want that, when i click to someone of this products, into my webpage appears a new box where there is the description of the product, the price etc..
This is the code for the products list
<?php
include 'php/dbmanager.php';
$result = DBManager::getInstance()->getProducts();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
echo "<div class=\"wrap effect8 open\" onclick>";
echo "<h1>".$row['product_name']."</h1>";
echo "<div class=\"left\">";
echo "<img src=".$row['product_image']." width=150 height=150 >";
echo "</div>";
echo "<div class=\"right\">";
echo $row['product_description'];
echo "<div class=\"prodSelection\">";
echo '<a href="catalogo.php?prodID=';
echo $row[product_id];
echo '"';
echo 'class="button">Acquista</a>';
echo '<label>';
echo '<select class="selectBoxCat">';
echo '<option selected> 1 </option>';
echo '<option>2</option>';
echo '<option>3</option>';
echo '</select>';
echo '</label>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
How can i get the ProductID ($row[product_id]) from a single product that i click and use it for a new query for select the database's rows of this single product (and use this query for make another php like that)?
I dont want to refresh the page.
Could i use the pushstate method (HTML5)?
If you want to get additional data when the user clicks, you will need to make an ajax request to update your DOM without refreshing the page.
On the PHP side, you'll want to create a script that returns a json-encoded value.
On the JS side, you'll want to create a click event listener. Inside the listener, you'll want to make an ajax request to your PHP script.
When your data is successfully returned from your ajax call, you'll want to manipulate your DOM to display your product's details.
Example of a click listener:
$("#button").on("click", function(){
// make your ajax request here
});
Example of an ajax call:
$.ajax({
method: "POST",
url: "scriptThatReturnsProductDetails.php",
data:
{
productID: $("#myProduct").attr('id')
}
})
.done(function( msg ) {
// Do some DOM manipulation
});
I'm building a web App for a friend, this is my first async site and I'm learning lots of cool stuff, but there are some details that make me struggle.
This is the general idea:
This simple app gets specific tables from a database using PHP and jQuery and shows them asynchronously on the page. There's this specific table (a waitlist) that shows all atributes from all entries on the table plus a small button that SHOULD delete that specific entry, the PHP code for the creation of the table is as follows:
<?php
include("con.php");
$result = mysqli_query($c,"SELECT * FROM waitlist");
echo "<thead>";
echo "<tr>";
echo "<th>Nombre</th><th>Sillas</th><th>Hora de Llegada</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID'] . ' id="deleteWaitlist">X</button>
</td>';
echo "</tr>";
}
echo "</tbody>";
mysqli_free_result($result);
?>
This is the table schema:
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL,
PRIMARY KEY(ID)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the best way of having the button delete the entry it apears on? The function refreshes the table every few seconds so deleting it from the database is all I need. I also have an incomplete PHP function that gets called on buttonpress that shold delete the entry, but Im unsure as to how to complete it. Here it is:
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
I need to replace the $_POST[name] with an identifier for the row, this is my problem. What's the best way of doing this? Can I pass it somehow though the jquery.ajax() call? Do I need a new table attribute ID? I'm sure the "this" keyword can be used somewhere. Is PHP and ajax even the best way of doing it?
Ajax writes the table on "#result_table", here's the relevant code if it's needed:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
</div>
EDIT: I updated the code as recomended by #vnponce
This is the code for the ajax call:
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
console.log(result);
}
});
});
After fiddling with the code I got rid of all errors and updated the post, but the entries are still not getting deleted.
The best way is creating an ID identifier in your table, then this identifier can be added in your 'Delete' button.
The button trigger a function that send ID, and your PHP file recive it and delete de data comparing the ID.
The identifier can be added in table schema ( i don't know if it is the rigth code, I always made in phpMyAdmin )
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL
);
First add the ID in delete photo.
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID']. ' "id="deleteWaitlist">X</button>
</td>';
The ajax
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({url: "YOUR_PHP_FILE.php", {id: i}, success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
// console.log(result);
}});
});
Now your PHP with ID
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
Well I hope help. If i have an error or you have a question let me know.
UPDATE*
Maybe there's an error deleteWaitlist.php , you can return error if it exist.
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
if ( ! mysqli_query($c,$sql) )
{
return "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
I managed to get quite far with another question last night but then I read that mysql_ was deprecated I switched to mysqli. Anyway I have the following php within my search.php file -ve kept some comments in which worked under my last attempt.
// Get all records
while ( $row = $results->fetch_assoc())
{
//$data[] = $row;
echo ('COLUMN1:'.$row["COLUMN1"]);
echo ('COLUMN2:'.$row["COLUMN2"]);
echo ('COLUMN3:'.$row["COLUMN3"]);
echo ('<br>');
}
$mysqli->close();
//echo json_encode( $data );
?>
And I want to display this data within a result div on my index.html page. I will eventually want to replace this data with a graph but one step at a time. I am struggling to understand how the data is passed between Ajax and php. This is my jquery/ajax:
$('#btn_search').click(function(){
txt_search = $('#txt_search').val();
$.ajax({
url: './php/search.php', //the script to call to get data
data: {search: txt_search}, //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
$('#result').append(rows);
}
}); return false;
});
I want to be able to write any columns from the DB table into the div, displaying as many rows as possible. I was originally using the following which wasn't quite working (only displaying 2 rows..I can see why (poor understanding of arrays I think):
/*for (var row in rows)
{
var COLUMN1 = rows[1];
var COLUMN2 = rows[2];
$('#result').append("<b>COLUMN1 </b>"+COLUMN1 e+"<b> COLUMN2: </b>"+COLUMN2).append("<hr />");
} */
EDIT: HTML
<div id="main">
<form id="search_form" role="form" action="" method="post">
<div class="form-group">
<input type="text" class="form-control" name="txt_search" id="txt_search" placeholder="Enter name here" autocomplete="off" >
<p></p>
<button type="submit" id="btn_search" class="btn btn-default">Retrieve </button>
</div>
</form>
<div class="result" id="result">this accessed by jquery and will be replaced</div>
/div>
Anyway I have a div called result which I would like to populate with a table of results just now. Can anyone answer and help me get a better understanding (I am finding a problem with this type of thing is there are hundreds of examples online, no explanation of why they doing what they are doing and all of them are different).
EDIT 2: Removed, Edit 3 contains better code:
EDIT 3: HTML into a variable:
$HTML = "<table border='1' >";
$HTML .= "<tr>";
$HTML .= "<td align=center> <b>Column1</b></td>";
$HTML .= "<td align=center><b>Column2</b></td>";
$HTML .= "<td align=center><b>Column3</b></td>";
// Get all records
while ( $row = $results->fetch_assoc())
{
$HTML .= '<tr>';
$HTML .= '<td align=center>'.$row["COLUMN1"].'</td>';
$HTML .= '<td align=center>'.$row["COLUMN2"].'</td>';
$HTML .= '<td align=center>'.$row["COLUMN3"].'</td>';
$HTML .= '</tr>';
}
$mysqli->close();
$HTML .= "</table>";
echo $HTML;
echo json_encode( $HTML );
?>
In this specific example just to demonstrate you can change the content of #result div by just using this in your success function:
$('#result').html(rows);
But normally you would create a some HTML structure in your search.php file and generate some HTML dynamically and then replace target #result div with that of returned by search.php.
Also you need to change the file extension of index.html to index.php
Edit: The cause is to remove datatype: json.