how to add ajax to a php file - php

how could i add ajax to my php file ,that when i delete an item of the list the data should automatically reload and my list should be updated to the new list?
I made list of all my data with a button of delete
here is my code for php
<?php
function tableV1 ($row) {
echo '<tr>';
echo '<td>' .$row['id']. '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
}
$dbPassword = "micr2001";
$dbUserName = "PHPFundamentals";
$dbServer = "localhost";
$dbName = "PHPfundamentals";
// Create connection
$conn = mysqli_connect($dbServer , $dbUserName , $dbPassword,$dbName) or die("unable to connect to host");
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<style type="text/css">
table {font-size: 27px; }
tbody {}
td {border-bottom: 1px solid bisque;padding:15px;}
th {border-bottom: 1px solid bisque;padding:15px;}
thead {}
tr {}
</style>
</head>
<body>
<center>
<table>
<thead>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
<th> </th>
</thead>
<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT id,firstname, lastname FROM persons";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
tableV1($row);
$rowId = $row['id'];
$first_name = $row['firstname'];
$last_name = $row['lastname'];
echo '<td>'
. ' <a class="edit_btn btn" href=edit.php?id='.$rowId.'&lname='.$last_name.'&fname='.$first_name. '>Edit</a>'
. ' </td>';
echo '<td><a class="del_btn btn" href=delete.php?id='.$rowId.'>Delete</a></td>';
echo' </tr>';
}
} else {
echo '<tr><td colspan="3">0 results</td></tr>';
}
?>
</table>
</center>
</body>
</html>
<?php
$conn->close();
?>
here is the code for delete.php
<?php
require 'connection.php';
$id = $_GET['id'];
$sql = "DELETE FROM persons WHERE id = ".$id ;
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
mysqli_close($conn);
?>
i want the item that i delete should get off my list

Why do you even need AJAX? As user clicks Delete, she / he is redirected to the delete.php script. In that script after sucessful deletion you should just redirect the user back to the listing. This can be achieved by HTTP redirect (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection). Keep it simple!

Related

Why is the record I wanted to delete still there even though I had the function up and running?

I am working on an assignment in PHP and MySQL, where I am needed to create a function to delete records from a table via ID with a push of a button with JavaScript. Even though I followed by teacher's videos, it still is not able to delete the record away.
My teacher and I suspected that it has got to do with the bind_param part, but still it is not solved.
Here are the files:
db-connect.php
<?php
$servername = "localhost";
$username = "root";
$password = ""; // this should be empty
$dbName = "newDB"; // add your database name here
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
/**
* $conn->connect_error - contains an error message from the database server (if any)
*/
}
?>
index.php
<?php
require "db-connect.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Code-Along 2</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>List of Records</h1>
<div>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Actions</th>
</tr>
<?php
$sql = "SELECT * FROM `Employee`;";
$sql_run = $conn->query($sql);
if($sql_run) { // if it is not false, then proceed
if($sql_run->num_rows > 0) { // num_rows will check if there are row(s) of results
while($row = $sql_run->fetch_assoc()) {
?>
<tr>
<td><?= $row['id']; ?></td>
<td><?= $row['name']; ?></td>
<td><?= $row['age']; ?></td>
<td><?= $row['email']; ?></td>
<td>
<button onclick="document.location.href = 'form.php?id=<?= $row['id']; ?>'">Edit</button>
<button onclick="deleteConfirm(<?= $row['id']; ?>);">Delete</button>
</td>
</tr>
<?php
}
} else {
// echo "No table rows found.";
?>
<tr>
<td colspan="5">No records found.</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="5">Error retrieving table rows: <?= $conn->error; ?></td>
</tr>
<?php
}
?>
</table>
</div>
<script src="main.js"></script>
</body>
</html>
main.js
function deleteConfirm(id) {
const response = confirm(`Are you sure you want to delete record #${id}?`);
if(response) {
document.location.href = "db-deleterecord.php?=id" + id;
}
}
db-deleterecord.php
<?php
if(isset($_GET['id'])) { // check if "?id=..." exists, i.e. if a GET value id is obtained.
require "db-connect.php";
$sql = "DELETE FROM `Employee` WHERE `id` = ?;";
$stmt = $conn->prepare($sql);
if($stmt) {
$stmt->bind_param("i", $_GET['id']);
if($stmt->execute()) {
echo "Deleted record with ID: " .$_GET['id'];
} else echo "Unable to delete record #" . $_GET['id'] . ": " .$stmt->error;
} else echo "Unable to prepare statement: " . $conn->error;
}
header("refresh:5; url=index.php");
?>
There's an error in your string concatenation for the url -
document.location.href = "db-deleterecord.php?=id" + id;
should be -
document.location.href = "db-deleterecord.php?id=" + id;

Why is PHP not displaying all values correctly?

Unfortunately my code isn't working quite well.
The source code:
<!DOCTYPE html>
<html>
<head>
<title>Query data from News database and display in table</title>
<meta charset="UTF-8">
<meta name="description" content="" />
<meta name="author" content="WRBikAir" />
<meta name="keywords" content="" />
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<?php
error_reporting(E_ALL);
echo "Test 1";
$con = mysqli_connect("mysql.hostinger.com","u441817146_admin","CBGApp","u441817146_cbg");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM News";
if ($result = mysqli_query($con, $sql)) {
echo "<table>";
while($row = $result->fetch_assoc()) {
$r = json_encode($row);
echo "<tr><td>" . $r['NID'] . "</td><td>" . $r['headline'] . "</td><td>" . $row['text'] . "</td><td>" . $r['timestamp'] . "</td></tr>";
}
echo "</table>";
} else {
echo "no result.";
}
mysqli_close($con);
echo "2";
?>
</body>
</html>
Everything works fine, except of the output of the NID, headline and timestamp. There are all '{'. Does it mean, that there is now value? because if I simply print them out (encoded of course) there are values e.g.:
{"NID":"1","headline":"Testartikel 2","text":"test test test","timestamp":"15.11.2017, 18:13"}
Does somebody knows a solution?
You are using $result 2 times on $result = mysqli_query($con, $sql) and in your foreach loop. I changed the one in the foreach loop to $results instead of $result.
Also try turning on error reporting using:
error_reporting(E_ALL);
Try using:
<!DOCTYPE html>
<html>
<head>
<title>Query data from News database and display in table</title>
<meta charset="UTF-8">
<meta name="description" content="" />
<meta name="author" content="WRBikAir" />
<meta name="keywords" content="" />
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<?php
echo "Test 1";
$con = mysqli_connect(CENSORED (but working in other classes fine);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM News";
if ($result = mysqli_query($con, $sql)) {
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo "<table>";
foreach ($resultArray as $results) {
$r = json_encode($results);
echo "<tr><td>" . $results['headline'] . "</td><td>" . $results['text'] . "</td></tr>";
}
echo "</table>"
}
mysqli_close($con);
echo "2";
?>
</body>
</html>
For everybody who need the working answer.
Thank you to MasterOfCoding, GrumpyCrouton, Paul Spiegel and prodigitalson.
Special thanks to tadman for the insider information.
Now the code:
<!DOCTYPE html>
<html>
<head>
<title>Query data from News database and display in table</title>
<meta charset="UTF-8">
<meta name="description" content="" />
<meta name="author" content="WRBikAir" />
<meta name="keywords" content="" />
<style>
table, th, td{
border: 1px solid black;
}
</style>
</head>
<body>
<?php
error_reporting(E_ALL);
echo "Test 1";
$con = mysqli_connect("...","...","...","...");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM News";
if ($result = mysqli_query($con, $sql)) {
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['NID'] . "</td><td>" . $row['headline'] . "</td><td>" . $row['text'] . "</td><td>" . $row['timestamp'] . "</td></tr>";
}
echo "</table>";
} else {
echo "no result.";
}
mysqli_close($con);
echo "2";
?>
</body>
</html>

Bootstrap Data Tables with MySQL content

I have a form in which a user select a reference of a candelabra.
When the choice done, a list of incidents relative to the candelabra appears in a bootstrap table.
The table is completed with items from a Mysql database.
All is ok. Now I'd like to add a button in another column called "test". But I have no buttons.. I put a screenshot of what I see..
My code is this one :
FORM FILE
<?php
require_once 'login.php';
$sql= "SELECT ptlum FROM ptlum where ptlum LIKE '%AZ%'";
$result = mysql_query($sql) or die("Requete pas comprise");
//while($data = mysql_fetch_array($result))
// {
//echo "<option>".$data[ptlum]."</option>";
// }
?>
<html>
<head>
<meta charset="utf-8">
<link href="examples.css" rel="stylesheet">
<link href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/lib/bootstrap.min.css" rel="stylesheet">
<link href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/lib/bootstrap-responsive.min.css" rel="stylesheet">
<link href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/custom.css" rel="stylesheet">
<link href="bootstrap.table.css" rel="stylesheet">
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form class="form-horizontal" >
<legend>Rechercher une panne en cours ou archivée</legend>
<div class="control-group">
<label class="control-label" for="selectbasic-0">Sélectionner un point lumineux</label>
<div class="controls">
<select name="users" onchange="showUser(this.value)">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option>".$row[ptlum]."</option>";
}
?>
</select>
</div>
</div>
</form>
<script src= "jquery.js"></script>
<script src= "bootstrap.min.js"></script>
<script src= "bootstrap.table.js"></script>
<br>
<div id="txtHint"><b></b></div>
</body>
</html>
PHP FILE WITH CALLING THE DATABASE
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<script src= "jquery.js"></script>
<script src= "https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script src= "https://cdn.datatables.net/1.10.9/js/dataTables.bootstrap.min.js"></script>
<?php
$q = $_GET['q'];
//echo $q;
$con = mysqli_connect('localhost','root','root','sdeer');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM depannages WHERE ptlum = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table id=\"example\" class=\"table table-striped table-bordered\" cellspacing=\"0\" width=\"100%\">
<tr>
<th>Pt Lum</th>
<th>Matériel</th>
<th>Prestation</th>
<th>Date</th>
<th>Nature</th>
<th>Test</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tbody>";
echo "<tr>";
echo "<td>" . $row['ptlum'] . "</td>";
echo "<td>" . $row['materiel'] . "</td>";
echo "<td>" . $row['presta'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['nature'] . "</td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
mysqli_close($con);
?>
<script>
$(document).ready(function() {
var table = $('#example').DataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
</script>
</body>
</html>
How to make it if I want to have a button ? When the user will click on the button, a new window will appear.
Thanks !
You can make a anchor tag look like as button. Just you need to add role="button".
New Window Button
Edited Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet">
<script src= "jquery.js"></script>
<script src= "https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script src= "https://cdn.datatables.net/1.10.9/js/dataTables.bootstrap.min.js"></script>
</head>
<body>
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','root','sdeer');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM depannages WHERE ptlum = '$q'";
$result = mysqli_query($con,$sql);
?>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Pt Lum</th>
<th>Matériel</th>
<th>Prestation</th>
<th>Date</th>
<th>Nature</th>
<th>Test</th>
</tr>
</thead>
<tbody>
<?
while($row = mysqli_fetch_array($result))
{?>
<tr>
<td><?echo $row['ptlum'];?></td>
<td><?echo $row['materiel'];?></td>
<td><?echo $row['presta'];?></td>
<td><?echo row['date'];?></td>
<td><?echo $row['nature'];?></td>
<td>
New Window Button
</td>
</tr>
<?}?>
<tbody>
</table>
<?mysqli_close($con);?>
<script>
$(document).ready(function() {
var table = $('#example').DataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
</script>
</body>
</html>

add/remove data from table from previous page

I have an HTML table being displayed from php data and I'm trying to move data from one table to another based on what is clicked. I cannot get it to move from table to another but I"m not getting any code error.
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests
</center>
</div>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
// get results from database
$result = mysql_query("SELECT * FROM temp")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['User_id'] . '</td>';
echo '<td>' . $row['First_name'] . '</td>';
echo '<td>' . $row['Last_name'] . '</td>';
echo '<td>' . $row['Username'] . '</td>';
echo '<td>Approve</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
</body>
</html>
PHP EDIT SCRIPT:
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests · All Users
</center>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
$id = $_GET['id'];
$sql = ("INSERT INTO users
SELECT * FROM temp WHERE User_id = $id ");
mysql_query($sql)
or die(mysql_error());
?>
</body>
</html>
I needed to use
$id = $_get['id];
and in the insert statement i had to replace id with User_id
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests · All Users
</center>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
$id = $_GET['id'];
$sql = ("INSERT INTO users
SELECT * FROM temp WHERE User_id = $id ");
mysql_query($sql)
or die(mysql_error());
?>
</body>
</html>

Populate a dropbox in PHP using MySQL and then display the data in a table after clicking submit button

I can populate correctly the dropbox but I cannot find a way to display the data of the selected item in a table when I click submit. Here is the code:
index.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Αναζήτηση Οφειλών Ανά Πολυκατοικία</title>
<link rel="stylesheet" href="tbl_style.css" type ="text/css"/>
</head>
<body>
<form id="form1" name="form1" method="POST" action="search.php">
<?php
include('config.php');
$query = "SELECT DISTINCT odos FROM ofeiles_results ORDER BY odos ASC";
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET NAMES 'utf8'");
$result = mysql_query($query);
echo "<select name='polykatoikia'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['odos'] . "'>" . $row['odos'] . "</option>";
}
echo "</select>";
?>
<input type="submit" name="Submit" value="Select" />
</form>
</html>
</body>
So far so good, the dropbox gets populated. Then in the file search.php I have the following code:
search.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Αποτελεσματα Αναζητησης Πολυκατοικιων</title>
<link rel="stylesheet" href="tbl_style.css" type ="text/css"/>
</head>
</html>
<?php
include('config_barcode.php');
if(isset($_POST['select'])){
$odoss = $_POST['select'];
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET NAMES 'utf8'");
$display_query = "SELECT odos FROM ofeiles_results WHERE odos LIKE '" . $odoss . "'";
$result_exoda = mysql_query($display_query) or die(mysql_error());
print $result_exoda;
$odos = $row['odos'];
$app = $row['perigrafh'];
$enoikos = $row['enoikos'];
$mhnas = $row['mhnas'];
$synolo = $row['synolo'];
echo "</br>";
echo "</br>";
echo "</br>";
echo "<table cellpadding='3' cellspacing='0'>";
echo "<tr>";
echo "<th align='center' bgcolor='#FFCC00'><strong>Οδος</strong></th>";
echo "<th align='center' bgcolor='#FFCC00'><strong>Διαμερισμα</strong></th>";
echo "<th align='center' bgcolor='#FFCC00'><strong>Όνομα</strong></th>";
echo "<th align='center' bgcolor='#FFCC00'><strong>Σύνολο</strong></th>";
echo "<th align='center' bgcolor='#FFCC00'><strong>Μήνας</strong></th>";
echo "</tr>";
echo "<td align='center'>".$odos."</td>";
echo " <td align='center'>".$app."</td>";
echo " <td align='center'>".$enoikos."</td>";
echo " <td align='center'>".$mhnas."</td>";
echo " <td align='center'>".$synolo."</td>";
echo "</table></td>";
echo $result_exoda;
}
?>
All I get is a blank page. What am I doing wrong? Thanks.
I use this to display the data in tables, you don't need to use many "echo" use LOOPS
you can add more rows in
$sql = "SELECT your_row , another_row , your_row_again FROM your_table_name";
if you had more rows in you database.
$conn = mysql_connect($dbhost, $dbuser);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT your_row , another_row , your_row_again FROM your_table_name";
mysql_select_db('your_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<div align = 'center'><table border = '1'>";
echo "<th>Your_row_Header</th><th>Row_Header_again</th><th>Row_Header_again</th>";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "<tr><td align = center>{$row['Your_row1']}</td>".
"<td align = center>{$row['Your_Row2']}</td></tr>".
"<td align = center>{$row['Your_Row3']}</td>";
}
echo "</table></div><br />";
mysql_close($conn);

Categories