Modifying the AJAX PHP database example - php

I would like to create something like this show here:
http://www.w3schools.com/PHP/php_ajax_database.asp
But instead of drop down list shown in the example, is it possible to change it to table format like example, when I click on the Class 1 it will display the details for class 1...the details are in my database its from phpmyadmin:
Thanks in advance...help greatly appreciated
Is this correct?
<?php
include ('staffheader.php');
?>
<div id="head">Permit Structure</div>
<div class="contents">
<div id="class_data">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td>Road Based</td>
<td>Proving Ground PG</td>
<td>Off Road OR</td>
<td>Towing TT</td>
</tr>
<tr id="Class_1">
<td> <a href='#' class='classlink' title='1'>Class 1</a></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Class 2</td>
<td>CAT 2PG</td>
<td>CAT 1OR</td>
<td>CAT 2TT</td>
</tr>
<tr>
<td>Class 3</td>
<td>CAT 3PG</td>
<td>CAT 2OR</td>
<td>CAT 3TT</td>
</tr>
<tr>
<td> </td>
<td>CAT 4PG</td>
<td>CAT 3OR</td>
<td> </td>
</tr>
</table>
</div>
<div id="instruction">Click on the Class or Category to view information on it</div>
</div>
<div id='detailtable'></div>
<?php
include('allfooter.php');
?>
loadergetclassinfo.php:
<?php
$class_id = empty($_POST["class_id"]) ? 1 : $_POST["class_id"];
$con = mysql_connect("localhost", "root", "cailing8195") or die ("Unable to connect to MySQL Server " . mysql_error());
if(is_resource($con))
$db = mysql_select_db("jlr", $con) or die( "Unable to select database " . mysql_error());
$query = "SELECT PTYPE, TYPE, PREREQ, DES FROM type WHERE TYID=" . $class_id;
$res = mysql_query($query);
$arr_data = mysql_fetch_assoc($res);
mysql_close($con);
foreach ($arr_data as $data)
$html = "<table>\n";
$html .= "<tr><th>Type ID</th><th>Permit Type</th><th>Categories</th><th>Pre-Requisisite</th><th>Description</th></tr>\n";
$html .= "<tr><td>" . $class_id . "</td><td>" . $data['PTYPE'] . "</td><td>" . $data['TYPE'] . "</td><td>" . $data['PREREQ'] . "</td><td>" . $data['DES'] . "</td> </tr>\n";
$html .= "</table>\n";
echo $html;
?>
JQuery (in javascript.js):
$(function() {
$('a.class_link').click(function() {
var class_id = $(this).attr('title');
$.post("loadergetclassinfo.php", {class: class_id}, function(result){
$('#detail_table').html(result);
});
});
});
And i add this inside my header php file too:
<script src="javascript.js"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>

If you want the row in which you click the link, to be populated with the data from the database, do something like this (untested, but here is the gist):
HTML:
<tr id='class_1'>
<td><a href='#' class='classlink' title='1'>Class 1</a></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
jQuery:
$(function() {
$('a.classlink').click(function() {
var class_id = $(this).attr('title');
$.post("loadergetclassinfo.php", {class_id: class_id}, function(result){
$('#class_' + class_id).html(result);
});
});
});
loadergetclassinfo.php:
<?php
$class_id = empty($_POST["class_id"]) ? 1 : $_POST["class_id"];
$con = mysql_connect("localhost", "your_MySQL_username", "your_MySQL_password") or die ("Unable to connect to MySQL Server " . mysql_error());
if(is_resource($con))
$db = mysql_select_db("your_MySQL_database", $con) or die( "Unable to select database " . mysql_error());
$query = "SELECT data1, data2, data3 FROM your_data_table WHERE class=" . $class_id;
$res = mysql_query($query);
$arr_data = mysql_fetch_assoc($res);
mysql_close($con);
$html = "<td><a href='#' class='classlink' title='$class_id'>Class $class_id</a></td>";
foreach ($arr_data as $data)
$html .= "<td>" . $data . "</td>\n";
echo $html;
?>
UPDATE:
If you want the 'Class x' data to appear somewhere else in your HTML page, you can maybe do something like this:
Add this to your HTML:
<div id='class_data'></div>
Change above jQuery like this:
$.post("loadergetclassinfo.php", {class: class_id}, function(result){
$('#class_data').html(result);
});
Change above php code to something like this (or you can use a list or whatever you like to see here):
$html = "<table>\n";
$html .= "<tr><th>Class Number</th><th>Data 1</th><th>Data 2</th><th>Data 3</th></tr>\n";
$html .= "<tr><td>" . $class_id . "</td><td>" . $data['data1'] . "</td><td>" . $data['data2'] . "</td><td>" . $data['data3'] . "</td></tr>\n";
$html .= "</table>\n";
echo $html;
This is assuming that you have columns called data1 etc and that your primary index is called 'class'. Just change it to what it is in your case.
UPDATE in RESPONSE TO YOUR EDITS:
End your HTML code with:
<div id='detailtable'></div>
Edit this jQuery statement:
$.post("loadergetclassinfo.php", {class: class_id}, function(result){
$('#detailtable').html(result);
});
Finally, remove the php code from below your HTML table, and put it in it's own file called "loadergetclassinfo.php" in the same directory as the HTML file.
ALSO, this is wrong (sorry, error was in my code):
$class_id = empty($_POST["class_id"]) ? 1 : $_POST["class"];
Should be:
$class_id = empty($_POST["class_id"]) ? 1 : $_POST["class_id"];
Also change the details table code to:
$html = "<table>\n";
$html .= "<tr><th>Type ID</th><th>Permit Type</th><th>Categories</th><th>Pre- Requisisite</th><th>Description</th></tr>\n";
$html .= "<tr><td>" . $class_id . "</td><td>" . $data['PTYPE'] . "</td><td>" . $data['TYPE'] . "</td><td>" . $data['PREREQ'] . "</td><td>" . $data['DES'] . "</td></tr>\n";
$html .= "</table>\n";

you can try to use ajax function from jquery it could be somethink like this again you could modify it.
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td>Road Based</td>
<td>Proving Ground PG</td>
<td>Off Road OR</td>
<td>Towing TT</td>
</tr>
<tr>
<td onclick="getPage(this)" >Class 1</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<div id='content'></div>
<script type="text/javascript">
function getPage(class) {
//generate the parameter for the php script
var data = 'page=' + document.location.hash.replace(/^.*#/, '');
$.ajax({
url: "loadergetclassinfo.php",
type: "GET",
data: (class).innerText,
cache: false,
success: function (html) {
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
</script>

Related

Why I cant click on rows of this table in html?

I have a dynamic table which I populate with data fetched from my db using PHP.
I tried following some tutorials and I could see that in their fiddle it was working but why doesn't it work on mine?
Could it be related to the scripts and links I am importing?
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#myTable').dataTable({
initComplete: function() {
this.api().columns().every(function() {
var column = this;
var select = $('<select class="browser-default custom-select form-control-sm"><option value="" selected>Filter</option></select>')
.appendTo($(column.footer()).empty())
.on('change', function() {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
$('#example tbody').on('click', 'tr', function() {
var data = table.row(this).data();
});
});
$('#myTable tr').each(function() {
// need this to skip the first row
if ($(this).find("td:first").length > 0) {
var cutomerId = $(this).find("td:first").html();
}
});
</script>
and the table below:
<table id="myTable" class="display compact" cellspacing="0" width="100%">
<thead>
<tr>
<th>Report ID</th>
<th>Client</th>
<th>Case</th>
<th>Date received</th>
</tr>
</thead>
<tbody>
<?php if (!empty($show_arr)) { ?>
<?php foreach ($show_arr as $user) {
if ($user['display'] == 1) {
?>
<tr>
<td>
<?php echo '<a href=selectedReport.php?rep_id=' . urlencode($user["id"]) . "&cus_id=" . urlencode($user["cus_id"]) . "&name=" . urlencode($user["name"]) . '>' . $user["id"] . '</a>'; ?>
</td>
<td>
<?php echo '<a href=selectedReport.php?cus_id=' . urlencode($user["cus_id"]) . "&rep_id=" . urlencode($user["id"]) . "&name=" . urlencode($user["name"]) . "&state=" . urlencode($user["state"]) . '>' . $user["name"] . '(' . $user["username"] . ')</a>'; ?>
</td>
<td>
<?php
echo '<a href=selectedReport.php?cus_id=' . urlencode($user["cus_id"]) . "&rep_id=" . urlencode($user["id"]) . "&name=" . urlencode($user["name"]) . "&state=" . urlencode($user["state"]) . '>' . $user['report_cases_accepted'][0]['case_id'] . '</a>';
?>
</td>
<td>
<?php
echo $user['date_sent'];
?>
</td>
</tr>
<?php
}
}
} ?>
</tbody>
<tfoot>
<tr>
<th>
</th>
<th>
</th>
<th>
</th>
<th>
</th>
</tr>
</tfoot>
</table>
My intention is to be able to click in rows and get the data you see in PHP and then redirect to another page. Basically, I want to do exactly the same what I am doing below using a href... but without it, now I just want to click anywhere in the rows, take the values of that row and redirect to next page.
Please let me know if there you see something wrong with the code above. My doubts are somewhere in the way I am importing the scripts and stylesheets but I am not sure.

Getting a specific row from PHP database to add to a new empty database upon clicking an "add to playlist button"

I have a group project for my web programming class, we are creating a simple music website and have created a database using phpmyadmin for each genre, we have a add to playlist button that should add the selected song to the empty database but we can not figure out why it is not working.
<div id="navbar">
<table>
<tr>
<td>
<font size="6"><b>Home</font>
</td>
<td>
<font size="6"><b>Pop</font>
</td>
<td>
<font size="6"><b>Hip-Hop</font>
</td>
<td>
<font size="6"><b>Rock</font>
</td>
<td>
<font size="6"><b>Country</font>
</td>
<td>
<font size="6"><b>Alternative</font>
</td>
<td>
<font size="6"><b>My Playlist</font>
</td>
</tr>
</table>
</div>
<!-- End of navbar div -->
<br>
<!-- PHP code here to display the appropriate databse table (genre/playlist) -->
<?php
$dbc = mysqli_connect("localhost", "root", "", "Music Website") or die("Bad Connect:" . mysqli_connect_error());
$sql = "SELECT * FROM AltMusic";
$result = mysqli_query($dbc, $sql) or die("Bad Query: $sql");
echo "<table id = 'database'>";
echo "<tr id = 'tableHead'>
<td class = 'titleCells'>Title</td>
<td class = 'titleCells'>Artist</td>
<td class = 'titleCells'>Album</td>
<td class = 'titleCells'>YouTube</td>
<td class = 'titleCells'>Genre</td>
<td class = 'titleCells'>Add to Playlist</td>
</tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td class = 'cells'>{$row['Title']}</td>
<td class = 'cells'>{$row['Artist']}</td>
<td class = 'cells'>{$row['Album']}</td>
<td class = 'cells'><a href='" . $row['YouTube'] . "'target = _blank>" .
$row['YouTube'] . "</a></td>
<td class = 'cells'>{$row['Genre']}</td>
<td id = 'add' class = 'cells'>" ?>
<form action='' method='POST'>
<input type='submit' name='submit' value="+"/>
</form><?
if (isset($_POST['submit'])) {
$sql2 = "INSERT INTO Playlist(`ID`, `Title`, `Artist`, `Album`, `YouTube`,
`Genre`)
SELECT `ID`, `Title`, `Artist`, `Album`, `YouTube`, `Genre`FROM Pop
WHERE ";
}
echo "</td>
</tr>";
}
echo "</table>";
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<br> Title: " . $row['Title'] . " Artist: " . $row["Artist"] . " Album: " .
$row["Album"] . "YouTube: " . $row["YouTube"] . "Genre: " . $row["Genre"] . "Add to Playlist: " .
$row["Add to Playlist"] . "<br>";
}
} else {
echo "0 results";
}
$dbc->close();
?>
<!-- Bookmark to allow uesrs to return to the top of the page once at the bottom -->
<a href=#top>
<font size="6">Back to top</font>
</a>
I have tried to use isset($_POST("") to add it but it can only figure out how to fetch the entire array instead on one single selection.
Please consider that I, as well as all of the members in my groups are fairly new to web programming. If I have not posted correctly or not given specific enough ideas about what I am trying to do please let me know in a considerate way. Thank you for any help you can provide.

How to properly set POST value from AJAX?

I want to pass the value from jquery to php using AJAX, the problem is the value in the php is not properly set.
Here is my sample codes:
Button trigger to pass data into jquery.
<button class="btn btn-info add-percentage"
data-landing_id-percentage="'.$row['hidden_id'] .'"
data-toggle="add-percentage"><i class="glyphicon glyphicon-time"></i></button>
Below is the ajax and jquery code.
<script>
$(".add-percentage").click(function(){
var landing_id = $(this).data('landing_id-percentage');
$.ajax({
url: 'ajax/readPercentage.php',
type: 'POST',
data: {
landing_id: landing_id
},
success: function(msg) {
alert('Email Sent'+msg);
$('#add-percentage').modal('show');
readRecords();
}
});
});
<script>
The result below in the php code is the landing_id is not properly set.
readPercentage.php
<?php
$data = '
<table class="table table-bordered table-hover table-striped" id="ModalMyTable">
<thead>
<tr class="success">
<th ><center>No.</center></th>
<th ><center>Percentage ID</center></th>
<th ><center>Landing ID</center></th>
<th><center>Percentage</center></th>
<th><center>Date Added</center></th>
</tr>
</thead>';
if(isset($_POST['landing_id'])){
$landing_id = $_POST['landing_id'];
$query = mysqli_query($conn, "SELECT
percentage.percent_id,
percentage.landing_id,
percentage.percentage,
percentage.date_recorded
FROM
percentage
WHERE percentage.landing_id = '$landing_id'");
$number = 1;
while($row = mysqli_fetch_assoc($query)) {
$data .= '
<tr>
<td><center>' . $number . '</center></td>
<td><center>' . $row['percent_id'] . '</center></td>
<td><center>' . $row['landing_id'] . '</center></td>
<td><center>' . $row['percentage'] . '%</center></td>
<td><center>' . date("M. d, Y", strtotime($row['date_recorded'])) . '</center></td>
</tr>';
$number++;
}
}else{
$data .='<tr><td colspan="6">Landing id is not properly set!</td></tr>';
}
$data .= '</table>
<script>
{
$(document).ready(function(){
$("#ModalMyTable").DataTable();
readRecords();
});
}
</script>
';
echo $data;
?>
I hope some one can help me in my problem. Thanks in advance.

Update data from query in table when select using ajax

My HTML code is very simple :
<body>
<form id="delForm" action="deleteThirdMulti.php" method="post"> <!--Le fomulaire qui ne sert que pour les checkbox-->
<div class="container">
<div class="col-md-1 pull-right">
<img src="CSS/PICTURES/add.png" />
<br /><br />
</div>
<div class="row">
<div class="col-md-2 form-group">
<button type="submit" class="btn btn-default" name="delete_all">Supprimer</button>
</div>
<div class="col-md-2 form-group">
<select name="choix_service" class="form-control form-update-user" id="sort">
<option selected="selected">TOUS</option>
<option value="COMPTABILITE">CLIENT</option>
<option value="EXPLOITATION">AFFRETE</option>
<option value="INFORMATIQUE">PROPRIETAIRE</option>
</select>
</div>
</div>
<table class="table table-condensed table-responsive table-bordered sortable table-striped" id="table">
<thead>
<tr>
<th class="text-center"><input type="checkbox" onclick="toggle(this)" name="check_all"/></th>
<th class="text-center">Type</th>
<th class="text-center">Code</th>
<th class="text-center">Nom</th>
<th class="text-center">Adresse 1</th>
<th class="text-center">Adresse 2</th>
<th class="text-center">Code Postal</th>
<th class="text-center">Ville</th>
<th class="text-center">Pays</th>
<th class="text-center">Téléphone</th>
<th class="text-center">Fax</th>
<th class="text-center">E-mail</th>
<th class="text-center">Site web</th>
</tr>
</thead>
<tbody>
And then, I have a PHP code which display datas from the database.
The problem is that I would like the user to be able to change the value in the select box and, I would like the datas to be updated without a page reload. Indeed, when I select CLIENT, only CLIENTS from the base will be displayed in the table.
My start of Jquery code :
<script type="text/javascript">
$(document).ready(function() {
$('#sort').change(function(){
var valeur = $('#sort option:selected').text();
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: valeur,
success: function(data) {
... do something with the data...
}
});
})
});
</script>
Inside your Success function on the Ajax call you will want to loop through the data and use jquery's
.html(text)
function to fill in the table data.
It may be easier to wrap the table id="table" inside a div container so you can write the entire table HTML from within your success function in the AJAX.
I hope this addresses your question, it was a little unclear what you are trying to accomplish, but it seems there is some language barriers here that we can hopefully overcome.
Let me know if you need any clarification on things!
Clarification for comment #1:
create a div on the page for your ajax response information. Let's call this "clients_table_container"
<div id="clients_table_container"></div>
When your ajax response success function is called, you can fill the content of this container div with the html code you would like to display. For Example:
success: function(data)
{
//TODO: Turn JSON into html string content
var my_html_string = data;
//REPLACE THE CONTENT IN THE DIV WITH THIS DATA
$('#clients_table_container').html(my_html_string);
}
You'll want to make sure you have the <table> html inside the my_html_string variable and you fill in the <tr><td></td></tr> tags based on the json response in the data variable. This part you will have todo as we have no visibility into it's contents.
It works !
This is my code in the AJAX PHP file :
<?php
include('../sqlConnexion.php');
include('../security.php');
if ($_POST['valeur'] == 'TOUS')
{
$req = $bdd->query('SELECT * FROM tiers ORDER BY code');
$response['i'] = $_POST['valeur'];
}
else
{
$req = $bdd->prepare('SELECT * FROM tiers WHERE type = :type ORDER BY code');
$req->execute(array(
'type' => $_POST['valeur']
));
}
$response['table'] = '';
$i = 0;
while ($third=$req->fetch())
{
$response['table'] = $response['table'] . "<tr>
<td align='center'><input type='checkbox' name='delete_$i' value='".$third['id']."'></td>
<td align='center'>" . $third['type'] . "</td>
<td align='center'>" . $third['code'] . "</td>
<td align='center'>" . $third['nom'] . " </td>
<td align='center'>" . $third['adresse1'] . " </td>
<td align='center'>" . $third['adresse2'] . " </td>
<td align='center'>" . $third['cp'] . " </td>
<td align='center'>" . $third['ville'] . " </td>
<td align='center'>" . $third['pays'] . " </td>
<td align='center'>" . $third['telephone'] . " </td>
<td align='center'>" . $third['fax'] . " </td>
<td align='center'>" . $third['email'] . " </td>
<td align='center'><a target='blank_' href='" . $third['website'] . "'>" . $third['website'] . " </td>
<td align='center'><a href='updateThird.php?id=" . $third['id'] . "'><img src='CSS/PICTURES/modification.jpg' title='Modifier le tiers'/></a></td>
</tr>";
$i++;
}
$req->closeCursor();
echo json_encode($response);
Here is my JQuery code with filling the 'tbody' :
$(document).ready(function() {
$('#sort').change(function(){
var valeur = $('#sort option:selected').text();
//window.location.replace('thirdManagement.php?third=' + valeur);
$.ajax({
url: 'MODEL/ajaxSearchThirds.php',
type: 'post',
dataType: 'json',
data: {'valeur': valeur},
success: function(data) {
$('tbody').html(data.table);
$('#ivalue').val(data.i);
}
});
})
});
Hope it will help someone.

Delete from html table made by database PHP

Here is the table below that I'm trying to delete rows out of:
<form method="POST" >
<table class="sortable">
<thead>
<tr>
<th id="makehead">Make </th>
<th id="modelhead">Model </th>
<th id="idhead">Delete </th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
foreach ($carArray as $k => $carInfo) {
$i++;
echo '<tr>';
if ($i % 2) {
echo '<td class="make">' . $carInfo['make'] . '</td>
<td class="model">' . $carInfo['model'] . '</td>
<td class="id"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
} else {
echo '<td class="makelight">' . $carInfo['make'] . '</td>
<td class="modellight">' . $carInfo['model'] . '</td>
<td class="idlight"><input type="checkbox" name="id" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
}
}
?>
</tr>
</table>
</tbody>
<td>
<input Onclick="return ConfirmDelete();" name="delete" type="submit" id="delete" value="Delete"></input>
</td>
</table></form>
As you can see i'm using checkboxes to tick each row then the delete button will have a confirm message then should delete but it doesn't here is my if statement:
if ($_REQUEST['delete']) {
$dbid = $_REQUEST['id'];
$db->setdbid($dbid);
So when this wasn't working I had a look on here and on other questions people said I need a setter function so i did this: EDIT: this is my class file.
public function setdbid($dbid){
$this->dbid=$dbid;
}
for this main function to delete things:
public function delete($dbid) {
try {
$sql = "DELETE FROM cars WHERE id = '$dbid'";
$this->db->exec($sql);
echo "Car has been deleted.";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
So that's all the relevant code I think, please help me if you can.
You just have to replace some piece of code in PHP :
if ($_REQUEST['delete']) {
$dbid = $_REQUEST['id'];
$db->delete($dbid); //Assuming delete is well a $db method, else replace it by the correct delete call
}
As you are using checkboxes with the same name, you have to change it so it's an array (and this way you'll be able to delete multiple rows at once) :
<td class="id"><input type="checkbox" name="ids[]" value="' . $carInfo['id'] . '">' . $carInfo['id'] . '</td>';
Then in your php code, treat this data as such :
if ($_REQUEST['delete']) {
foreach($_REQUEST['ids'] as $id){
$xxx->delete(intval($id)); //convert to integer to avoid sql injection.
}
}
Note that you don't need to set $db->setdbid since you pass that id as a parameter of your delete method.

Categories