Displaying search result on same page without refreshing the page - javascript

While browsing a website i found an interesting feature that i like to have in my application.It is like displaying search result on same page without refreshing the page. When someone fills the last field of the form it shows the search result on the same page without refreshing the page.The form has no submit button or any link to submit the form data when someone fills the last field it search result and display the result. I want to implement this feature in my application i built in PHP. I know this can be done by Javascript & Ajax but i don't have enough knowledge of these languages. I just learned HTML,CSS,PHp & MySql. Let me show u my code
HTML:
<form action="do_search.php" method="post"/>
Enter Number:<input type="text" name="roll" id="roll">
<input type="submit" value="search record"/>
do_search.php:
<?php
include 'includes/dbConnect.php';
?>
<?php
$roll = $_POST['roll'];
$result = mysql_query( "SELECT * FROM students WHERE Roll_No = '$roll'" ) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
?>
<table width="100%" bgcolor="#F7F7F7" border="0">
<?php
if ($num_rows!=0)
{
?>
<tr style="text-align:left;">
<td width="7%" align="center" bordercolor="#CCCCCC" bgcolor="#996600" class="heading"><strong>#</strong></td>
<td width="13%" align="left" bordercolor="#CCCCCC" bgcolor="#996600" class="heading"><strong>Roll No</strong></td>
<td width="29%" align="left" bordercolor="#CCCCCC" bgcolor="#996600"class="heading"><strong>Name</strong></td>
<td width="23%" align="left" bordercolor="#CCCCCC" bgcolor="#996600" class="heading"><strong>Father Name</strong></td>
<td width="16%" align="center" bordercolor="#CCCCCC" bgcolor="#996600" class="heading"><strong>Class</strong></td>
<td width="12%" align="center" bordercolor="#CCCCCC" bgcolor="#996600" class="heading"><strong>Section</strong></td>
</tr>
<?php
//$counter = 1;
while ($get_info = mysql_fetch_row($result))
{
print '<tr class="text-data">';
print '<td align="center" valign="top">' . $get_info[0] . '</td>';
print '<td align="left" valign="top">
<a href="edit_Student.php?roll_no=' . $get_info[1] . '" style="color:#000"><b>' . $get_info[1] . '</b></td>';
print '<td align="left" valign="top">'. $get_info[2] . '</td>';
print '<td align="left" valign="top">' . $get_info[3] . '</td>';
print '<td align="center" valign="top">' . $get_info[4] . '</td>';
print '<td align="center" valign="top">' . $get_info[5] . '</td>';
print '</tr>';
//$counter++;
}
}
else
{
?>
<tr style="text-align:left;">
<td align="center" colspan="7">
No Student Found !
</td>
</tr>
<?php
}
?>
</table>
This is working fine for me and display the record on do_search.php page. I want my form has no submit button option & when someone enter the form field Enter Roll Number it should display the record on same page and display all the record from database. Can anyone please help me for this. Thanks in advance

You can do that with jQuery ajax.
<form action="do_search.php" method="post"/>
Enter Number:<input type="text" name="roll" id="roll">
</form>
<div id="result"></div>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$("#roll").change(function() {
$.post("do_search.php", { roll:$("#roll").val() })
.done(function( data ) {
$("#result").html(data);
});
});
</script>

Use Jqyery keydown() Method
$("input").keydown(function(){
//Do display logic
// Use Ajax and get the data for the value enter and update your html content
});
http://www.w3schools.com/jquery/event_keydown.asp

Related

Post recordset to a table, then select one row and post to another page

I recently ran into a problem I wasn't quite sure how to solve. Sharing it here in case it helps someone else.
Use Case: User enters a string in a search box on a PHP page. On submit, the page queries the database and then posts results to a table on the same page. User then selects a single record with a radio button and needs to post only that record to a different PHP page. The second page does not have access to the database.
I took the actual page and created a sample page for clarity and testing, since the original had about 15 table columns.
<div class="container">
<div class="row" style="margin-top: 1rem;">
<div class="col-sm">
<form action="" method="post">
<table class="fit" id="entry">
<tr>
<td class="fit"><label for="start">Planet (try <strong>Caprica</strong> or <strong>Picon</strong>): </label></td>
</tr>
<tr>
<td class="fit"><input type="test" id="planet" name="planet" required autofocus /></td>
</tr>
</table>
<input class="btn btn-primary" type="submit" value="Get Characters" />
</form>
</div>
</div>
</div>
<div class="container" style="margin-top: 2rem;">
<div class="row">
<div class="col-sm">
<?php
require_once('./resources/pdo.php');
if ( isset($_POST['planet']) ) {
$planet = strtolower($_POST['planet']);
$pdo = new myPDO('phppostpost');
try {
$stmt = $pdo->prepare('CALL devCharacters(?)');
$stmt->bindParam(1, $planet, PDO::PARAM_STR);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error occurred: " . $e->getMessage());
}
?>
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead class="thead-light">
<tr>
<th class="fit">Select</th>
<th class="fit" scope="col">Customer First</th>
<th class="fit" scope="col">Customer Last</th>
<th class="fit" scope="col">Planet</th>
</tr>
</thead>
<tbody>
<?php while ($r = $stmt->fetch()): ?>
<tr>
<?php echo "<td class='fit'><input type='radio' id='cust-" . $r['customer_id'] ."' name='cust-id' value='". $r['customer_id'] . "' </td>"; ?>
<?php echo "<td class='fit'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['origin_planet'] . "</td>"; ?>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<input class="btn btn-primary" onclick="getSelectedRowData();" type="submit" value="Send" />
<?php } ?>
</div>
</div>
</div>
As a relatively new developer, I couldn't figure out how to (1) grab just the selected row and (2) post data on submit from just that row, rather than from the the original search form.
After much Googling, as well as a kick in the pants from a Stack Overflow user who reminded me I needed to actually research for more than 20 minutes (thank you!), I was able to solve it.
I'll post the answer below for anyone else who runs into a similar problem.
To solve this, I used JavaScript to grab the selected row. In order to efficiently grab the correct record, I updated each TD element to have a unique, dynamically-generated ID:
<?php echo "<td class='fit' id='fname-" . $r['customer_id'] ."'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='lname-" . $r['customer_id'] ."'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='planet-" . $r['customer_id'] ."'>" . $r['origin_planet'] . "</td>"; ?>
I also gave the table body an ID so I could grab it quickly without grabbing a parent, then children, etc.:
<tbody id="results-body">
Finally, here's the JavaScript.
function getSelectedRowData() {
const tableRowArray = Array.from([document.getElementById('results-body')][0].rows);
let custFirst;
let custLast;
let custPlanet;
tableRowArray.forEach((tableRow, i) => {
cellButton = tableRow.getElementsByTagName('input');
if (cellButton[0].checked == true ) {
const rowID = cellButton[0].id.split('-').pop();
custFirst = document.getElementById('fname-' + rowID).innerHTML;
custLast = document.getElementById('lname-' + rowID).innerHTML;
custPlanet = document.getElementById('planet-' + rowID).innerHTML;
}
});
/* Build a hidden form solution to prep for post.
Source: https://stackoverflow.com/questions/26133808/javascript-post-to-php-page */
let hiddenForm = document.createElement('form');
hiddenForm.setAttribute('method', 'post');
hiddenForm.setAttribute('action', 'newpage.php');
hiddenForm.setAttribute('target', 'view');
const fieldCustFirst = document.createElement('input');
const fieldCustLast = document.createElement('input');
const fieldCustPlanet = document.createElement('input');
fieldCustFirst.setAttribute('type', 'hidden');
fieldCustFirst.setAttribute('name', 'custFirst');
fieldCustFirst.setAttribute('value', custFirst);
fieldCustLast.setAttribute('type', 'hidden');
fieldCustLast.setAttribute('name', 'custLast');
fieldCustLast.setAttribute('value', custLast);
fieldCustPlanet.setAttribute('type', 'hidden');
fieldCustPlanet.setAttribute('name', 'custPlanet');
fieldCustPlanet.setAttribute('value', custPlanet);
hiddenForm.appendChild(fieldCustFirst);
hiddenForm.appendChild(fieldCustLast);
hiddenForm.appendChild(fieldCustPlanet);
document.body.appendChild(hiddenForm);
// Post
window.open('', 'view');
hiddenForm.submit();
}
This worked for me, but I'm sure there's a better way to do this. Hopefully this (1) helps someone else and (2) a better solution is posted!
Here's a working demo: https://postfrompost.paulmiller3000.com/
Full source here: https://github.com/paulmiller3000/post-selected-from-post

Save updated values to database and show them in html table

I have a table like the following:
<script>
$("#edit").hide(); // Hide the edit table first
$("#update").click(function() {
$("#edit").toggle();
$("#shown").toggle();
// If we are going from edit table to shown table
if($("#shown").is(":visible")) {
var vouchertype = $('input[name="vouchertype[]"]').map(function(){return $(this).val();}).get();
var mode= $('select[name="mode[]"]').map(function(){return $(this).val();}).get();
// Then add it to the shown table
var baseurl='<?php echo base_url()."index.php/account/insert_voucher";?>';
$.ajax({
type: "POST",
url: baseurl,
data: $('#edit *').serialize() ,
cache: false,
success: function(html) {
alert(html);
}
});
$(this).val("Edit");
}
else $(this).val("Update");
});
</script>
<table width="62%" height="70" border="1" cellpadding="0" cellspacing="0" class="tbl_grid" id="shown">
<?php if(count($voucher_info) > 0 ){ ?>
<tr class="bgcolor_02">
<td width="22%" height="25" align="center" class="admin" >S.no</td>
<td width="37%" align="center" class="admin">Voucher Type</td>
<td width="37%" align="center" class="admin">Voucher Mode</td>
</tr>
<?php
$rownum = 1;
foreach ($voucher_info as $eachrecord){
$zibracolor = ($rownum%2==0)?"even":"odd";
?>
<tr align="center" class="narmal">
<td height="25"><?php echo $eachrecord->voucher_id; ?></td>
<td><?php echo $eachrecord->voucher_type; ?></td>
<td><?php echo ucwords($eachrecord->voucher_mode); ?></td>
</tr>
<?php }
}
else {
echo "<tr class='bgcolor_02'>";
echo "<td align='center'><strong>No records found</strong></td>";
echo "</tr>";
}
?>
</table>
<table width="62%" height="70" border="1" cellpadding="0" cellspacing="0"
id="edit">
<?php if(count($voucher_info) > 0 ){ ?>
<tr class="bgcolor_02">
<td width="27%" align="center" class="admin" >S.no</td>
<td width="37%" align="center" class="admin" >Voucher Type</td>
<td width="47%" align="center" class="admin" >Voucher Mode</td>
<!-- <td width="41%" align="center" class="narmal"> <strong>Actions</strong></td>-->
</tr>
<?php
$rownum = 1;
foreach ($voucher_info as $eachrecord){
$zibracolor = ($rownum%2==0)?"even":"odd";
?>
<tr align="center" class="narmal">
<td height="25"><?php echo $eachrecord->voucher_id ; ?><input type="hidden" name="voucher_id[]" value="<?php echo $eachrecord->voucher_id; ?>" /></td>
<td><input name="vouchertype[]" type="text" value="<?php echo $eachrecord->voucher_type; ?>" /></td>
<td><select name="mode[]" >
<option value="paidin" <?php if($eachrecord->voucher_mode=='paidin') { ?> selected="selected" <?php } ?>>Paid In</option>
<option value="paidout" <?php if($eachrecord->voucher_mode=='paidout') { ?> selected="selected" <?php } ?>>Paid Out</option>
</select></td>
</tr>
<?php } }
else {
echo "<tr class='bgcolor_02'>";
echo "<td align='center'><strong>No records found</strong></td>";
echo "</tr>";
}
?>
</table>
</td>
</tr>
<input id="update" type="submit" name="submit" value="Edit"/
In first table I am displaying values from database. But when user click on edit button below the table, Then that table values should be editable for user. I have succeeded in making editable fields but again when user click on submit then updated values are not displaying in first table. I know it's possible with jQuery or JavaScript. When I alert(newsales), the alert is undefined.
An easy way to handle this would be have two separate tables, and toggle between them when you edit a table. So for example we have a table that shows our normal data called shown and one with the input and select for a user to enter data called edit. These tables will share the same button, and when clicked it will toggle between the tables, making it look like it's switching between edit and show mode. This way we can just copy the values from the edit table to the text in the shown table. Here is an example:
$("#edit").hide(); // Hide the edit table first
$("#update").click(function() {
$("#edit").toggle();
$("#shown").toggle();
// If we are going from edit table to shown table
if($("#shown").is(":visible")) {
// Get the data from the edit table
var newSales = $("#edit tr:nth-child(1) td input[name='vouchertype']").val();
var newPay = $("#edit tr:nth-child(1) td select[name='mode']").val();
var newTax = $("#edit tr:nth-child(2) td select[name='tax']").val();
// Then add it to the shown table
$("#shown tr:nth-child(1) td:nth-child(2)").text(newSales);
$("#shown tr:nth-child(1) td:nth-child(3)").text(newPay);
$("#shown tr:nth-child(2) td:nth-child(1)").text(newTax);
$(this).val("Edit");
}
else $(this).val("Update");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="shown">
<tr>
<td>Sr no</td><td>Sales</td><td>Paid in</td>
</tr>
<tr><td>Taxed</td></tr>
</table>
<table id="edit">
<tr>
<td>Sr no</td><td><input type="text" name="vouchertype" value="Sales" /></td>
<td>
<select name="mode">
<option value="paidin">Paidin</option>
<option value="paidout">Paidout</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="tax">
<option value="Taxed">Taxed</option>
<option value="Not Taxed">Not Taxed</option>
</select>
</td>
</tr>
</table>
<input id="update" type="submit" name="submit" value="Edit"/>
Notice: This is an answer to the original question, which is quite different then the new question added in as an edit.

How to Check if other page field value is empty using jquery

I'm getting all contacts from Mysql db and then showing it on html row. Each row has onClick() method After click on each row it will show a details of contact to the right side of all contacts.
showing All contacts:
echo "<tr onclick='getDetails($cdid), showthirdbox($cdid), visited(this);'>";
echo "<td class='' valign='top' align='left' width='20'>$companyName</td>";
echo "<td class='' valign='top'>$family_name</td>";
echo "<td class='' valign='top'>$given_name</td>";
echo "<td class='' valign='top'>$department</td>";
echo "<td class='' valign='top'>$title</td>";
echo "</tr>";
This getDetails() call the getContactDetails.php (Contact Details) page. In this page I've a field called Note where user can enter notes.
So now I want to show a Confirm message to the user Only if user write something on Enter Note box but click other row (all contacts) without save this Enter Notes
Confirm mesaage will be : Do you want to save this Notes box before you go to other Contact ? Yes Or No. If Yes then saveNote() will be call otherwise it will load the new contact row.
I've no idea how can I do this using Jquery or Javascript ? Do you have any idea or solution ? Thank you.
getDetails() function:
function getDetails(id) {
id = id;
$.ajax({
type:"post",
url:"getContactDetails.php",
data:"id="+id,
success:function(res){
$('#visiable').show();
$('#notebox_visiable').show();
$('#thirdBox').show();
$('#all_contact_details').html(res);
showthirdbox(id);
//showNotexBox(id);
//showAllNotesBox(id);
}
});
}
getContactDetails.php page have Note field:
<tr>
<td colspan="2">Enter Note<p id="demo"></p></td>
</tr>
<tr>
<td colspan="2">
<center><img id="loading-image" src="images/loading-image.gif" style="display:none; margin-bottom:10px !important;"/></center>
<div id="Notesboxsuccess"></div>
<form action="" method="post" id="showNotesBox" name="notebox">
<input type="hidden" value="<?php echo $id; ?>" name="cdid" id="cdid"/>
<tr>
<td colspan="2"><textarea name="contentText" id="contentText" cols="35" rows="4" placeholder="enter note"></textarea></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save" name="submit" class="submit" id="addNewNotes"/></td>
</tr>
</form>
Home page view after click on a row (All contacts) :
change only triggers on blur, so as long as the user stays in the textbox there is nothing to do.
jQuery change()
Attach a change event handler:
$("#contentText").change(function() {
$("#contentText").attr("ididwritesomething","yep");
}
In the save button remove the attribute jQuery removeAttr()
$("#contentText").removeAttr("ididwritesomething");
In the click handler for your contact list, check if the attribute is set (from this question):
var attr = $("#contentText").attr("ididwritesomething");
if (typeof attr !== typeof undefined && attr !== false && attr=="yep"){
//do you want to save?
}
Here you can use jQuery Change function to do this.
For example,
<input id="field" type="text" value="abcd">
<a id="pid" href="#">Link</a>
For the above html code the jQuery code is following
$(document).ready(function(){
$("#pid").click(function(){
$("#field").change(function(){
alert("The text has been changed.");
});// end of change
});// end of click function
});//end of document

Input from textbox and file in PHP form

I have tried making a html and php page for taking input and processing them respectively. In the HTML page, user is given a option of either give a text or upload the file.
<form action="target.php" method='POST' enctype="multipart/form-data" id="form">
<table width="950px" align="center">
<tr>
<table width="100%" align="center" cellpadding="0" cellspacing="0" class="table1" border="0">
<tr valign="middle" align="left"><td width="15" height="10"></td><td></td></tr>
<tr valign="middle" align="left">
<td width="15"></td>
<td><font color="White">input1</font>
<td width="15"></td>
<td>
<font color="Red"><input type="file" name="file" size="42"><br></font><font color="White">or paste below:</font><br>
<textarea name="sequence1" cols="96" rows="7"></textarea><br>
</font>
</td>
</tr>
</table> </form>
Similarly in the PHP page, i could succesfuly transfer the uploaded file from the html page to a varible and run the shell script but unable to process the content from textbox.
<?php
$a = $_FILES['file']['tmp_name'];
$c = (isset($_POST['sequence1'])) ? $_POST['sequence1'] : false;
if($a!=NULL)
{
$output=shell_exec("sh server.sh $a");
}
elseif ($c!=NULL){
$output=shell_exec("sh server.sh $c");}
else{
echo "No input";}
?>
Can anybody help me to solve this problem or other way you could help me would be text input variable to converted to a file for the shell script
If I understand you well, this is what you need to do:
<?php
if(isset($_POST['sequence1'])){
//get the input content
$textInput = $_POST['sequence1'];
//temp file name
$file = 'temp.txt';
// Write the contents back to the file
file_put_contents($file, $textInput);
$output=shell_exec("sh server.sh $file");
}else{
echo "No input";
}
?>
Parse error in your php code.
echo No input;
It should be
echo "No input";

How to refresh php table by var obtained via javascript

I'm coding a mini web project to learn about php/html/java. The page I'm coding contains a table that use php code in it. This php code allows me to connect to my db and get the values I want to show in the table. Then I have a select box that has return the value of the selected field (via javascript?). This value has to be used refresh the php table. So the value has to be sent to the php code (via Ajax?) and refresh the query I make to my db so the table will show new values. This is waht I have now:
<html>
<head>
<title>Test</title>
<style type="text/css">
body {
background-color: #9C3;
}
p {color:black;}
.table_test {
font-family: Constantia, Lucida Bright, DejaVu Serif, Georgia, serif;
}
</style>
</head>
<body><div align='center'>
<p> </p>
<p>test!</p>
<p> </p>
<div class="table_test">
<table border='1' cellpadding='0' cellspacing='0' width='600' bgcolor='#F6F6F6' bordercolor='#FFFFFF'>
<tr>
<td width='150' style='font-weight: bold'></td>
<td width='150' style='font-weight: bold'>Festa</td>
<td width='150' style='font-weight: bold'>Preu</td>
<td width='150' style='font-weight: bold'>Entrada</td>
<td width='150' style='font-weight: bold'>Final</td>
<td width='150' style='font-weight: bold'>Estil</td>
<td width='150' style='font-weight: bold'>Llista</td>
</tr>
<?php
include ('connection.php');
include ('functions.php');
$dw = date("w");
echo "Avui es el dia: $dw";
$query = 'SELECT disco_id, party_name, price, hin, hout, style, list FROM disco_var WHERE day = '.$dw;
$result = mysql_query($query,$connect);
while ($reg = mysql_fetch_array($result))
{
$disco_id = $reg['disco_id'];
$disco_name = get_disco_name_from_id($disco_id);
$hin = substr($reg['hin'],0,5);
$hout = substr($reg['hout'],0,5);
$price = $reg['price'];
if ($reg['list'] == 1) $list = "Apunta't!";
else $list = "-";
echo "<tr>
<td width='150'>".$disco_name."</td>
<td width='150'>".$reg['party_name']."</td>
<td width='150'>".$reg['price']." e</td>
<td width='150'>".$hin."</td>
<td width='150'>".$hout."</td>
<td width='150'>".$reg['style']."</td>
<td width='150'>".$list."</td>
</tr>";
}
include ('close_connection.php');
?>
</table>
</div>
<p>Veure un altre dia de la setmana:
<select name="day_select" id="day_select" onchange="dayChanged(this);">
<option value="1">Dilluns</option>
<option value="2">Dimarts</option>
<option value="3">Dimeces</option>
<option value="4">Dijous</option>
<option value="5">Divendres</option>
<option value="6">Dissabte</option>
<option value="0">Diumenge</option>
</select>
</p>
<script type="text/javascript"> //Here is the problem!!
function dayChanged(opt)
{
//What should be the code here?
}
</script>
</body>
</html>
So I want de var in php $dw to get refreshed by the value of the option selected in the select box (onClick function). Then the other problem is how to refresh the table with this $dw value.
I'm new with php/html/java coding and I'm really stucked with it. Thank you.

Categories