How to hide the result table on search bar? - javascript

I am not really good in coding, I need a help with my code. I have a code to search in a database. Now it's showing all the data on the database, when somebody search, it will filter out and show me result on the same table.I only want to show the result, when somebody search on the search bar, it should show me the filtered data. otherwise, my table should be hidden.
Can anybody please tell me how to do that. Thank you so much for your time.
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `ADDRESS` WHERE CONCAT(`ID`, `STATE`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `ADDRESS`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost:3306", "root", "dbadmin", "simplymac");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>SimplyMac PO Tracking Tool</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<style>
</style>
</head>
<body>
<div class="images-wrapper">
<img class="Large" src="/dbadmin/Images/simplymac_logo.png" width="320" height="140" />
</div>
<form action="index.php" method="post">
<div class="wrap">
<center><h3>PO TRACKING TOOL</h3></center>
<center><table>
<tr>
<td><input type="text" name="valueToSearch" placeholder="Enter Purchase Order (PO#) Number" size="100" class="searchbar"></td>
<td><input type="submit" name="search" value="SEARCH" class="Button"></td>
</tr>
</table></center>
</div>
<table class="resultdata">
<tr>
<th>ID</th>
<th>ADDRESS_LINE_1</th>
<th>ADDRESS_LINE_2</th>
<th>CITY</th>
<th>STATE</th>
<th>ZIP</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['ID'];?></td>
<td><?php echo $row['ADDRESS_LINE_1'];?></td>
<td><?php echo $row['ADDRESS_LINE_2'];?></td>
<td><?php echo $row['CITY'];?></td>
<td><?php echo $row['STATE'];?></td>
<td><?php echo $row['ZIP'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>

You can use ajax for your problem.
When customer type in text box at that time call one java script function, in this function get text box value and call ajax for result table.
function getResult(search)
{
var file_path = '';//your php file path
$.ajax({
type: "POST",
url: file_path,
data: search,
cache: false,
success: function(result){
//print result in one div
}
});
}
<input type="submit" name="search" value="SEARCH" class="Button" onClick="getResult(this.value);">

Related

Popup content dependent on AJAX result

I am not that experienced in web developing, so sorry for rookie mistakes;)
In HTML, I want to create a dynamic popup window(div hidden by CSS). On the click of a button I am performing an AJAX post request. The result of the request is a string, which is stored in a hidden input field on the HTML page.
The popup contains a table with the content submitted by the string.
However now I want to retrieve the string via a PHP $_GET or $_POST request.
This is not working at the moment and I don't understand why.
Opening the popup window I am getting these errors:
Notice: Undefined index: popupcontenthidden in ...
Warning: Invalid argument supplied for foreach() in
The HTML:
<div class="popupcontent">
<span class="helper"></span>
<div>
<div class="popupclose">X</div>
<h3>UPDATE DATABASE ENTRY</h3>
<h4>Enter values:</h4>
<table id="popupresult">
<form name='form' action="" method='post'>
<input type='text' name='popupcontenthidden' id='popupcontenthidden'>
</form>
<tr>
<th>Field</th>
<th>Type</th>
<th>Null</th>
<th>Key</th>
<th>Default</th>
<th>Extra</th>
<th>Value</th>
</tr>
<?php
$rows = json_decode($_POST['popupcontenthidden']);
foreach ( $rows as $print ) {
?>
<tr>
<td><?php echo $print->Field; ?></td>
<td><?php echo $print->Type; ?></td>
<td><?php echo $print->Null; ?></td>
<td><?php echo $print->Key; ?></td>
<td><?php echo $print->Default; ?></td>
<td><?php echo $print->Extra; ?></td>
</tr>
<?php } ?>
</table>
</div>
The JS:
$.ajax({
type:'POST',
url: '../wp-content/plugins/ars-management/admin/ars-management-admin-ajax.php',
data: {function: "update", entries: entries},
success: function(response) {
var rows = response;
//hand data to html hidden input
document.getElementById("popupcontenthidden").value = rows;
//open popup on click
$(".popupcontent").show();
}
});
I understand that the second error is happening because $rows is empty.
But how can I fix the issue and retrieve the string from the input field? I can confirm that the string is correctly stored in the input field so all the AJAX stuff works.
Thank you so much!
A kind of solution here:
HTML:
<div class="popupcontent">
<span class="helper"></span>
<div class="popupclose">X</div>
<h3>UPDATE DATABASE ENTRY</h3>
<h4>Enter values:</h4>
<table id="popupresult">
<thead>
<tr>
<th>Field</th>
<th>Type</th>
<th>Null</th>
<th>Key</th>
<th>Default</th>
<th>Extra</th>
<th>Value</th>
</tr>
</thead>
<tbody id="myPopupContentTableBody"></tbody>
</table>
</div>
Javascript:
$.ajax({
type:'POST',
url: '../wp-content/plugins/ars-management/admin/ars-management-admin-ajax.php',
data: {function: "update", entries: entries},
success: function(response) {
$('#myPopupContentTableBody').html(response);
//open popup on click
$(".popupcontent").show();
}
});
PHP:
<?php
...
$rows = myPHPCalculation;
foreach ($rows as $print){
echo '
<tr>
<td>'.$print['Field'].'</td>
<td>'.$print['Type'].'</td>
<td>'.$print['Null'].'</td>
<td>'.$print['Key'].'</td>
<td>'.$print['Default'].'</td>
<td>'.$print['Extra'].'</td>
</tr>
';
}
...

PHP - Notice: Undefined index: and not displaying data

this is code of search.php. i want to take search by date from the input box as below.
<form action="visitor-print.php">
<div class="col-sm-3 text-center"><h3>Date</h3>
<input type="text" class="form-control" name="dat" placeholder="Enter Date">
<p class="help-block">Month Format 1,2,3,....29,30..</p>
<button class="btn btn-default"><span>Submit</span></button>
</div>
</form>
this is my visitor-print.php code where i get undefined index error on dat (which is from the other page)
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('visitor_list');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM list1 WHERE d1 = '". $_POST["dat"] . "' ";
$retval = mysql_query( $sql,$conn ) or die("Error: ".mysql_error($conn));
?>
<div class="container">
<h3 class="text-center">User Feed-Back Details</h3><br />
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<tr>
<th width="10%">Visitor Name</th>
<th width="10%">Address</th>
<th width="10%">Area to Visit</th>
<th width="10%">Phone No.</th>
<th width="20%">Want to meet with </th>
<th width="50%">Purpose of meeting</th>
</tr>
<?php
while($row = mysql_fetch_array($retval,MYSQLI_BOTH))
{
?>
<tr>
<td><?php echo $row['nm']; ?></td>
<td><?php echo $row['add1']; ?></td>
<td><?php echo $row['area_vis']; ?></td>
<td><?php echo $row['y1']; ?></td>
<td><?php echo $row['app_ty']; ?></td>
<td><?php echo $row['no_per']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
<div align="center">
<button name="create_excel" id="create_excel" class="btn btn-success">Create Excel File</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('#create_excel').click(function(){
var excel_data = $('#employee_table').html();
var page = "excel.php?data=" + excel_data;
window.location = page;
});
});
</script>
Problem:
Notice: Undefined index: dat in D:\wamp\www\radissun visitor\visitor-print.php on line 12
and is not showing data from mysql
The answer you are looking for: You are using $_POST - which is just for forms which have method="post". Default method is GET - so your variables are $_GET[]. You can either set the method parameter in the html to POST, or you change your PHP code to GET.
But I must point out, that your code is not usable for productive environments, as it is vulnerable to SQL Injection. See http://www.w3schools.com/sql/sql_injection.asp
MISSING METHOD ON FORM METHOD="POST"
NOTE: IF YOU USE METHOD="POST" YOU CAN GET VALUE BY $_POST['dat']; IF YOUR NOT USING METHOD ATTRIBUTE .FORM JUST SUBMITED AS GET METHOD YOU CAN GET BY $_GET['dat'];
<form action="visitor-print.php" METHOD="POST" >
MISSING FORM SUBMIT
<INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="SUBMIT" >
(OR)
ADD TYPE="SUBMIT" TO BUTTON
<button TYPE="SUBMIT" class="btn btn-default"><span>Submit</span></button>

Updating SQL data without refreshing page

I'm trying to update the two locked textboxes with information that I get from my database. I enter a phone number in the "Telefon" checkbox, and I want it to get the firstname and lasttname for that phone number. Which works by the way, but it's not the way I want it. I want the information to be automatically put into the textboxes without refreshing the page. and for some odd reason my code got split in two here. I've tried to look for a solution for hours. I'm very new to coding, and I would love some help!
<?php
SESSION_START();
$output = NULL;
if(isset($_POST['btn_checkTelefon'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$fornavnoutput_Database = $rows['Fornavn'];
$etternavnoutput_Database = $rows['Etternavn'];
}
echo '<script type = "text/javascript">';
echo 'function sayHi() {';
echo 'val1 = document.getElementById("telefon_Input").value;';
echo 'if(val1 == "") {';
echo ' alert("Vennligst skriv inn ditt telefon nummer!");';
echo '}';
echo 'if(val1 !== "") { ';
echo ' document.getElementById("check_Fornavn").value = "<?php echo $fornavnoutput_Database?>";';
echo ' document.getElementById("check_Etternavn").value = "<?php echo $etternavnoutput_Database?>";';
echo '}';
echo '}';
echo '</script>';
} else {
$output = "No results";
}
}
$fornavnoutput_Database2 = "Fornavn";
$etternavnoutput_Database2 = "Etternavn";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
</script>
<script type = "text/javascript"></script>
<title></title>
</head>
<body>
<?php
include 'connectdb.php';
?>
<form name="form1" action="">
<table id="valgt_skap_tabell" class="bokssvartabell">
<tr>
<td>Valgt skap</td>
</tr>
<tr>
<td>
<input class="bokssvarskjema" type="text" name="Valgt skap" disabled value= <?php
if(isset($_POST["radios"])){
echo $_POST["radios"];
} else {
//header('location: index.php');
} ?>>
</td>
</tr>
</table>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button type="button" name ="btn_checkTelefon" id="sjekkTelefon" onclick = "sayHi()">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
</form>
<?php echo $output; ?>
</body>
You need to use AJAX for this. Example $.ajax() -> shortcuts $.post(), $("id").load("url"), ... Look it up a lot in depth explanation about these on stackoverflow.
Please never mix JavaScript with php.
Use it in separate file.
Edit: So have you fixed it yet?
The easier way to load paged dynamicaly is with load method + actions. $.post is used if you need to do something with returned data from php. I will give you example of load.
I will give a proper example how to code.
Universal function for a link that look at href value and load HTML parts (form in this case) from PHP dynamicaly to your page, you do need to implement actions or just call your ordinary page if you have only one default action there. I use jQuery library here. This script must be in separate file else it will work but you will get a sync warning in your console.
$(function() {
$('a').on("click", function(e) {
e.preventDefault();
e.stopPropagation();
var URL = $(this).attr('href');
$('body').load(URL, 'form');
})
})
php example
prefered showsomethingfunction in separate file like showfunctions.php
function myLinks() {
echo "<a href='index.php?action=showsomething'>showsomething</a>"
}
index.php + included showfunctions.php
<?php
myLinks();
if(isset($_GET["action"]){
// do your ordinary thing like open connection with database.
switch($_GET["action"]))
{
case "showsomething":
//show showsomething() function with html
break;
//further you can add more action instead of showsomething if you have several links
}
//close database.
}
?>
You need to separate your code else it will be a mess if it gets even more complicated. HTML code must be ONLY in showfunctions.php for example in function to call for actions.
Code is not tested but I think it will work. This code will also work without javascript but then it will just reload pages.
You have to use jQuery $.post() for that.
first You have to create php file which will process Your data.
For example lets create file query.php with the following content:
<?php
if(isset($_POST['telefon_Search'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
$row = $resultSet->fetch_assoc();
echo json_encode($row);
}
}
next on Your page You have to create function which will send phone number to our query.php file and which will return Name and Surname if they exist.
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
var user = $.parseJSON(data);
$('#check_Fornavn').val(user.Fornavn);
$('#check_Etternavn').val(user.Etternavn);
});
});
and complete html will looks like:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
<title></title>
</head>
<body>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button name ="btn_checkTelefon" id="sjekkTelefon">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
$('#check_Fornavn').val(data.Fornavn);
$('#check_Etternavn').val(data.Etternavn);
});
});
</script>
</body>
</html>

PHP - pass hidden value into the jquery

<html>
<head>
<link rel="stylesheet" href="js/jquery-ui-themes-1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.11.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
</script>
</head>
<body>
<?php
//db connection
$query = "SELECT *
FROM department
ORDER BY dept_ID ASC";
$result = mysqli_query($dbc, $query);
$total_department = mysqli_num_rows($result);
if($total_department > 0)
{
?>
<table width="600" border="1" cellpadding="0" cellspacing="0" style="border-collapse:collapse">
<tr>
<td width="80" align="center">ID</td>
<td width="300" align="center">Department</td>
<td width="220" align="center">Action</td>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button class="buttonsPromptConfirmDeleteDepartment">Delete</button>
<input type="hidden" id="departmentID" value="<?php echo $row['dept_ID']; ?>" />
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
department table
dept_ID dept_name
1 Account
2 Finance
3 Marketing
Assume that my department table only have 3 records.
My requirement is the following:
- Click 1st delete button, show department ID = 1
- Click 2nd delete button, show department ID = 2
- Click 3rd delete button, show department ID = 3
However from my code, I can't meet my requirement. The department ID output that I get is 1 no matter what button I clicked.
Can someone help me?
No need to use a hidden input, you could just use the button tag instead:
<?php while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button type="submit" name="departmentID" class="buttonsPromptConfirmDeleteDepartment" value="<?php echo $row['dept_ID']; ?>">Delete</button>
</td>
</tr>
<?php } ?>
Of course, in the PHP script that does the form processing, access the POST index like you normally would:
$id = $_POST['departmentID'];
// some processes next to it
Note: Don't forget the <form> tag.
Additional Note: Don't forget to use prepared statements:
$sql = 'DELETE FROM department WHERE dept_ID = ?';
$stmt = $dbc->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
// some idea, use error checking when necessary
// $dbc->error
Change
id="departmentID"
to
class="departmentID" and
Change
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
to
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $(this).next('input.departmentID').val();
alert(departmentID);
});
});
first of all dept_id in while loop and you are using same id for all dept..
another thing you can get dept_id upon button click using jquery.. like this
$('.buttonsPromptConfirmDeleteDepartment').click(function(){
dept_id = $(this).next('input').val();
})

Load php file with ajax

Im using ajax to load the testNew.php file into the Cart.html file. It loads the testNew.php file but when i click on the button add which is in the testNew.php, 0 is being entered in the database and as soon as i click on the add button the page refresh by itself. My problem is that i dont want the page to refresh and want the add button to do the same action as in the testNew.php file(which works correctly).
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.js'>
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("#product").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "testNew.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
</head>
<body>
<table border="1">
<tr>
<td>
<input type="button" id="product" name="product"value="View all products"/>
</td>
</tr>
</table>
<div id="responsecontainer"></div>
Here is the testNew.php which works correctly.
<?php
include'connect.php';
$image = isset($_REQUEST['image']) ? $_REQUEST['image'] : "";
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : "";
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : "";
$price= isset($_REQUEST['price']) ? $_REQUEST['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo ($row['id']); ?></td>
<td><img src=<?php echo $row['image'] ?> width='120'
height='100'/></td>
<td><?php echo htmlspecialchars($row['name']); ?></td>
<td><?php echo htmlspecialchars($row['price']); ?></td>
<td>
<form method="POST" action="" >
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="hidden" name="image" value="<?php echo $row['image']; ?>" />
<input type="hidden" name="price" value="<?php echo $row['price']; ?>" />
<input id="submit" type="submit" name="submit" value='Add to cart'
onclick="add()"/>
</form>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id', '$name','$price')";
$insertQuery=mysql_query($insert);
?>
Your error in thought is actually that you are including a form through AJAX of which the HTML is then loaded into your page after which the action attribute on the form refers to the page itself (loading HTML into your page with AJAX does not work the same as an iframe) which does not have the relevant code to actually parse and insert the database.
You need to make a separate page that only accepts a few parameters and inserts those into the database. However, before you do that you need to read this:
I'm going to go off on the safety of your code for a tad.
$_REQUEST refers to both $_GET and $_POST, you really want only $_POST as you just want to deal with what gets submitted through a form.
You never sanitize your input, this way a person could craft an URL with say phpNew.php?id='; DROP TABLE wooptiedoo. This is a simplified example but nevertheless you should take a closer look at the mysql_real_escape_string documentation and possibly some guides on "sql injection".
After that those same variables can be used for XSS which means someone can use your page to serve random HTML to people visiting that site and trusting your domain. I suggest you look up the htmlentities function and/or read up on "cross-site scripting" attacks.
And to end it all, the mysql_* functions are deprecated and you should probably be using mysqli_* functions.

Categories