I new to php, ajax and mysql. I am trying to build a web application where i get an output table from my database. My question is what code should i use if i want to search another table using the current output table for eg
name surname
john smith
is my out put table, if i click on smith it should search other table containing data about smith
My js code is
$(function myFunction() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
var value1= $('#str1').val();
$.post('test_refresh.php',{value:value,value1:value1}, function(data){
$("#search_results").html(data);
});
return false;
});
});
My Php code is
<?php
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
$db = mysql_select_db("cancer database") or die(mysql_error());
echo"";
/*$query = mysql_query("SELECT * FROM tbl_cancer_database
WHERE gene_symbol LIKE '".$_POST['value']."'
OR gene_name LIKE '".$_POST['value']."'
OR gene_id LIKE '".$_POST['value']."'
OR gene_locus LIKE '".$_POST['value']."'
OR function LIKE '%".$_POST['value']."%'
OR alteration_in_cancer LIKE '".$_POST['value']."'
OR reference LIKE '".$_POST['value']."'
");*/
$query = mysql_query("SELECT * FROM tbl_cancer_database
WHERE gene_name LIKE '".$_POST['value']."'
and gene_id LIKE '".$_POST['value1']."'
");
echo '<br />';
echo "You have searched for ".$_POST['value']." and ".$_POST['value1']."";
echo '<br />';
echo '<br />';
echo '<table>';
echo "<tr>
<th bgcolor=silver>Sr. No.</th>
<th bgcolor=silver>Gene Symbol</th>
<th bgcolor=silver>Gene Name</th>
<th bgcolor=silver>Gene Id</th>
<th bgcolor=silver>Gene locus</th>
<th bgcolor=silver>Function</th>
<th bgcolor=silver>Alteration in cancer</th>
<th bgcolor=silver>Reference</th></tr>";
while ($data = mysql_fetch_array($query)) {
echo '<tr style="background-color:pink;">
<td>'.$data["id"].'</td>
<td>'.$data["gene_symbol"].'</td>
<td>'.$data["gene_name"].'</td>
<td>'.$data["gene_id"].'</td>
<td>'.$data["gene_locus"].'</td>
<td>'.$data["function"].'</td>
<td>'.$data["alteration_in_cancer"].'</td>
<td>'.$data["reference"].'</td>
</tr>';
}
echo '</table>';
?>
Any help would be greatly appreciated.
First of all add a class that uniquely identifies each of your table data.
So your table would look like this
<table>
<tr>
<td class="fistname">John</td>
<td class="lastname">Smith</td>
</tr>
</table>
Then your javascript would look like this
$(function myFunction() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
var value1= $('#str1').val();
$.post('test_refresh.php',{value:value,value1:value1}, function(data){
$("#search_results").html(data);
initializeClick();
});
return false;
});
});
function initializeClick(){
$('.firstname').click(function(){
var sSearchValue = $(this).text();
$.post('PAGE TO SEARCH YOUR OTHER TABLE',{value:sSearchValue}, function(data){
//CAN DO WHAT EVER YOU WANT WITH THE RESULTS HERE
});
});
}
Also keep in mind to escape characters when they are output on the html
Related
I have an input field with the date type, and there is a database that contains data with dates. I need that when selecting a date in the date field without refreshing the page, all the data associated with this date will be displayed. I have this code, which, when choosing an option from the list, will display what I need. how to fix this script so that when a date is selected in a date type field, it sends the date to the server
<input type="date" class="form-control" name="date_sched" value="" required>
<span id="skidka"></span>
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var category = $(this).find(':selected').val();
$.ajax({
url:_base_url_+"admin/appointments/get_cat.php",
type: 'POST',
data: {category: category},
success: (function (data) {
$("#date_field").html(data);
})
});
});
});
get-cat.php
$query = "SELECT * FROM `appointments` WHERE `id` = '".($_POST['category'])."'";
$result = $mysqli->query($query);
$data = '';
foreach ($result as $value){
$data .= $value['date_sched'];
}
echo $data;
?>
For retrieving data using Ajax + jQuery, you should write the following code:
Create an HTML button with id="showData". Ajax script will execute on click this button.
backend-script.php
<?php
include("database.php");
$db=$conn;
// fetch query
function fetch_data(){
global $db;
$query="SELECT * from usertable ORDER BY id DESC";
$exec=mysqli_query($db, $query);
if(mysqli_num_rows($exec)>0){
$row= mysqli_fetch_all($exec, MYSQLI_ASSOC);
return $row;
}else{
return $row=[];
}
}
$fetchData= fetch_data();
show_data($fetchData);
function show_data($fetchData){
echo '<table border="1">
<tr>
<th>S.N</th>
<th>Full Name</th>
<th>Email Address</th>
<th>City</th>
<th>Country</th>
<th>Edit</th>
<th>Delete</th>
</tr>';
if(count($fetchData)>0){
$sn=1;
foreach($fetchData as $data){
echo "<tr>
<td>".$sn."</td>
<td>".$data['fullName']."</td>
<td>".$data['emailAddress']."</td>
<td>".$data['city']."</td>
<td>".$data['country']."</td>
<td><a href='crud-form.php?edit=".$data['id']."'>Edit</a></td>
<td><a href='crud-form.php?delete=".$data['id']."'>Delete</a></td>
</tr>";
$sn++;
}
}else{
echo "<tr>
<td colspan='7'>No Data Found</td>
</tr>";
}
echo "</table>";
}
?>
ajax-script.js
$(document).on('click','#showData',function(e){
$.ajax({
type: "GET",
url: "backend-script.php",
dataType: "html",
success: function(data){
$("#table-container").html(data);
}
});
});
You need to make it so that when your date changes, you fetch data based on that date:
<input type="date" class="form-control" name="date_sched" id='date_sched' required>
<script type='text/javascript'>
$(document).ready(function(){
$(document).on('change', '#date_sched', function(){
let date = $(this).val();
$.ajax({
url:_base_url_+"admin/appointments/get_cat.php",
type: 'POST',
data: {date: date},
success: function (data) {
$("#data_to_be_shown").html(data);
);
});
});
});
</script>
Your query then, should look something like this:
$date = $_POST['date'];
$sql = "SELECT * FROM `table_name` WHERE `date` = $date";
$stmt = $connection->query($sql);
Also I recommend you look up prepared statements.
Im not sure what you want, are you mean server side table with date filter?
If yes, I think this will help:
https://datatables.net/examples/data_sources/server_side
You can read the docs for advance costume date range filter or for your own filter
I am developing online attendance.But I stuck in while loop condition
I want to show my code first
<tbody>
<?php
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
$stmt = $user->atten();
while($ro22 = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><input name ="uname" id ="uname" onBlur="checkAvailability2()" style ="border:none" value = "<?php echo $ro22['user_id'] ?>"/></td>
<td><?php echo $ro22['first_name'] ?> <?php echo $ro22['last_name'] ?></td>
<td><?php echo $ro22['parent_contact'] ?></td>
<td><input type="button" value="<?php echo $ro22['ai'] ?>" id="pres" name="pres" onclick="return change(this);" onBlur="checkAvailability()" class="w3-button w3-teal"/></td>
</tr>
<?php } ?>
</tbody>
This is output
What I want
I want update present,absent value based on 101,102,103... value
I tried many but failed. Please help me out
Thanks in advance
You need to place a call to the page on a click and pass the user_id. This is easy to do with jQuery:
function change(row) {
$.post('thispage.php', { user_id: $(row).val() }, function(){ window.location.reload(); } );
}
And then receive the post in the PHP:
if (!empty($_POST['user_id'])) {
/* toggle admission status */
}
After the request completes and the status is toggled, the page will reload.
Here is a general example. It's consisted of your PHP program (the AJAX sender) which I rewrote to be they way I think you wanted, a javascript file (containing the AJAX function) and another PHP file (the AJAX request receiver).
You can get different use-cases by altering the database query in the receiving PHP file.
Javascript file (AJAX):
// Send the `id` of the element
function checkAvailability(id)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
// This `if` underneath is success. It means we got a response back
if (this.readyState == 4 && this.status == 200)
{
if(this.responseText == "OK")
{
alert('ID: ' + id + ' changed. Response: ' + this.responseText);
document.getElementById("demo").innerHTML = 'The student has been updated.';
}
else if(this.responseText == "Not OK")
{
alert('Something went wrong with id: ' + id);
}
}
};
// For example you send a request to attendance.php sending `id` info
// - attendance.php just needs to echo the response to answer back
xhttp.open("GET", "attendance.php?id=" + id, true);
xhttp.send();
}
Main PHP page (the file that sends the request):
// U need jQuery to be able to send AJAX requests. Copy this, add to your html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
$stmt = $user->atten();
echo '<table>
<tr>
<th>Student ID</th>
<th>Student name</th>
<th>Phone number</th>
<th>Today\'s attendance</th>
</tr>';
while($ro22 = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>
<td><input name ="uname" id ="uname" onBlur="checkAvailability2()" style ="border:none" value="'.$ro22['user_id'].'"/></td>
<td>'.$ro22['first_name'].' '.$ro22['last_name'].'</td>
<td>'.$ro22['parent_contact'].'</td>
<td><input type="button" value="'.$ro22['ai'].'" id="pres" name="pres" onclick="change(this.id);" onBlur="checkAvailability(this.id)" class="w3-button w3-teal"/></td>
</tr>';
}
echo '</table>';
?>
The receiver file:
<?php
$conToDatabase = ... // Here goes DB connection data
if(isset($_GET['id']) && ctype_digit($_GET['id']))
{
$clean['id'] = $_GET['id'];
}
// Query your DB here using variable $clean['id'] as ID
$querySuccess = ...
// if query successful echo 'OK';
// else echo 'Not OK';
?>
I tried to write a code for a progress bar using PHP, JQuery and HTML.
So, I made a Ajax Request for a PHP file and in the success Ajax parameter I search a data requested from PHP File like this..
success: function(data){
if(data == 'Error1'){
alert("The File is not a .csv");
}else if(data == "Error2"){
alert("Please select a file to import!");
}else{
$('#consumidor_table').html(data);
alert("The importation has been made!");
}
}
That else does print a Table with MySql DB lines. The PHP file read a .csv from a HTML input and insert those lines in DB.
Actually, my code to do a progress bar is it:
Before at success parameter
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(evt.loaded);
console.log(evt.total);
console.log(percentComplete*100);
addProgress(percentComplete*100);
}
});
return xhr;
},
The entire codes:
JQuery;
PHP URL
The Error: When a upload a file and submit the form, the console.log(evt.total); and console.log(evt.loaded); print the same value, and them the progress bar is fully, but the Ajax continues requesting the PHP file and my table is empty yet.
So what I can do to my progress bar work with the response from PHP file?
I am not sure about the loading, Even I am in search of something that shows how much is complete. But I have a working code to upload CSV to Mysql.
<?php
if(!empty($_FILES["employee_file"]["name"]))
{
$connect = mysqli_connect("123.123.123.99","db_username","db_password","db_Name") or die('Unable To Connect');
$output = '';
$allowed_ext = array("csv");
$extension = end(explode(".", $_FILES["employee_file"]["name"]));
if(in_array($extension, $allowed_ext))
{
$file_data = fopen($_FILES["employee_file"]["tmp_name"], 'r');
fgetcsv($file_data);
while($row = fgetcsv($file_data))
{
$customerDetails = mysqli_real_escape_string($connect, $row[0]);
$cod = mysqli_real_escape_string($connect, $row[1]);
$trackingID = mysqli_real_escape_string($connect, $row[2]);
$shipmentType = mysqli_real_escape_string($connect, $row[3]);
$vendorName = 'eKart';
$query = "
INSERT INTO nss_delivery
(customerDetails, cod, trackingID, shipmentType, vendorName)
VALUES ('$customerDetails','$cod', '$trackingID', '$shipmentType', '$vendorName')
";
mysqli_query($connect, $query);
}
$select = "SELECT * FROM nss_delivery ORDER BY deliveryID DESC";
$result = mysqli_query($connect, $select);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="25%">Customer Details</th>
<th width="35%">COD Amount</th>
<th width="10%">Tracking ID</th>
<th width="20%">ShipmentType</th>
<th width="5%">Vendor Name</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["deliveryID"].'</td>
<td>'.$row["customerDetails"].'</td>
<td>'.$row["cod"].'</td>
<td>'.$row["trackingID"].'</td>
<td>'.$row["shipmentType"].'</td>
<td>'.$row["vendorName"].'</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
else
{
echo 'Error1';
}
}
else
{
echo "Error2";
}
?>
I am trying to display the contents of a "users" table in my MYSQL database using PHP,JQUERY and JSON.
Here is the PHP file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "ITSM";
$tableName = "signup_and_login_table";
include 'database_connection.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
On my HTML page i have a simple table im trying to target:
<table id="personDataTable">
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</table>
This is the jquery ajax, I want it to loop through all the users and other table entities to display all the contents of the Database table on the page, Im currently just getting "undefined".
$(function ()
{
$.ajax({
url: 'CMGetdata.php',
data: "",
dataType: 'json',
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
console.log("test");
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row);
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
}
Any assistance to be pointed in the correct direction would be greatly appreciated thanks.
Try This-
$result =$con->query("SELECT * FROM tableName");
$array = $result ->fetch_all(MYSQLI_ASSOC);
foreach($array as $array)
{
$array['example'];
//another
}
I have a webpage http://skywateryachts.com/disp_new.php where I formatted the currency with no problem.
However, the sorting of the listed price appears to be by order of the first several digits rather than total value. Example, $110,000 appears before $110,900,000 when sorted descending.
The MySQL field type is INT and I just formatted the SELECT statement for the currency symbol.
I'm using the dataviewer extension in the WYSISWYG Webbuilder and custom formatting the code. But I am new to customizing MySQL.
I'm thinking it would be better to eliminate the sort feature and do it myself but would like first to know what the issue could be with the sorting of the digits.
Thanks
Pertinent code:
<script type="text/javascript">
$(document).ready(function()
{
$.fn.alternateRowColors = function()
{
$('tbody tr:odd', this).removeClass('even').addClass('odd');
$('tbody tr:even', this).removeClass('odd').addClass('even');
return this;
};
$('table.sortable').each(function()
{
var $dataviewer = $(this);
$dataviewer.alternateRowColors();
$('th', $dataviewer).each(function(column)
{
var $header = $(this);
var findSortKey;
findSortKey = function($cell)
{
return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
};
if (findSortKey)
{
$header.addClass('clickable').hover(function()
{
$header.addClass('hover');
}, function()
{
$header.removeClass('hover');
}).click(function()
{
var sortDirection = 1;
if ($header.is('.sorted-asc'))
{
sortDirection = -1;
}
var rows = $dataviewer.find('tbody > tr').get();
$.each(rows, function(index, row)
{
var $cell = $(row).children('td').eq(column);
row.sortKey = findSortKey($cell);
});
rows.sort(function(a, b)
{
if (a.sortKey < b.sortKey) return -sortDirection;
if (a.sortKey > b.sortKey) return sortDirection;
return 0;
});
$.each(rows, function(index, row)
{
$dataviewer.children('tbody').append(row);
row.sortKey = null;
});
$dataviewer.find('th').removeClass('sorted-asc').removeClass('sorted-desc');
if (sortDirection == 1)
{
$header.addClass('sorted-asc');
}
else
{
$header.addClass('sorted-desc');
}
$dataviewer.find('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
$dataviewer.alternateRowColors();
});
}
});
});
<div id="dataviewer" style="position:absolute;overflow:auto;left:269px;top:390px;width:803px;height:980px;z-index:46">
<?php
$mysql_host = 'localhost';
$mysql_user = 'xxxx';
$mysql_password = 'xxxx';
$mysql_database = 'xxxx';
$mysql_table = 'boats';
$db = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $db);
$sql = "SELECT Date_Listed, Est_DOM, LOA, Builder, Built, Currency, concat('$', format(Listing_Price, 0)), NFS_USA FROM ".$mysql_table;
$result = mysql_query($sql, $db);
?>
<table cellpadding="0" cellspacing="1" width="100%" class="sortable paginated">
<thead>
<tr>
<th>List Date</th>
<th> Est DOM</th>
<th> Length</th>
<th> Builder</th>
<th> Year Built</th>
<th> Currency</th>
<th> Listing Price</th>
<th> NFS USA</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_row($result))
{
echo " <tr>\n";
foreach ($row as $cell)
{
echo " <td>" . $cell . "</td>\n";
}
echo " </tr>\n";
}
?>
</tbody>
</table>
</div>
You probably are sorting by your formatted column in the field list of your SELECT. Instead, in your ORDER BY reference the name of the integer column directly from your table.
So if you have this:
SELECT FORMAT(foo, '$99,999,999.99')
FROM bar
ORDER BY 1
instead do this
SELECT FORMAT(foo, '$99,999,999.99')
FROM bar
ORDER BY foo
(Ignore the actual syntax of the formatting - I always have to look that stuff up to get the right function and syntax and I'm just doing it for an example.)