A newbie question so please be kind :)
I've made a small search script to lookup values in my database.
But when I put in a search result I'm getting all the files in my database. Not just the name I looked for. I'm not a technical person so I was wondering where my mistake sits.
Main search page
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
function search(){
var name=$("#search").val();
if(name!=""){
$("#result").html("<img src='ajax-loader.gif'/>");
$.ajax({
type:"post",
url:"search-database.php",
data:"name="+search,
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
}
$("#button").click(function(){
search();
});
$('#search').keyup(function(e) {
if(e.keyCode == 13) {
search();
}
});
});
</script>
</head>
<body>
<div id="container">
<input type="text" id="search" placeholder="Zoek hier uw kandidaat...."/>
<input type="button" id="button" value="Zoek" />
<ul id="result"></ul>
</div>
</body>
</html>
search-database.php
<?php
include 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gevonden kandidaten</title>
</head>
<body>
<div id="header">
<label>Resultaten</label>
</div>
<div id="body">
<table width="80%" border="1">
<tr>
<td>File Name</td>
<td>File Type</td>
<td>File Size(KB)</td>
<td>View</td>
</tr>
<?php
$search=$_POST['search'];
$query = $pdo->prepare("select * from test where name LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, PDO::PARAM_STR);
$query->execute();
while($results= $query->fetch())
{
?>
<tr>
<td><?php echo $results['name'] ?></td>
<td><?php echo $results['type'] ?></td>
<td><?php echo $results['size'] ?></td>
<td>view file</td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
Replace your search function with
function search(){
var name=$("#search").val();
if(name!=""){
$("#result").html("<img src='ajax-loader.gif'/>");
$.ajax({
type:"post",
url:"search-database.php",
data:"name="+name,
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
}
Here :
var name=$("#search").val();
You're setting your input value to a variable named name, but here :
data:"name="+search,
You're sending a non-existent value named search to your PHP file (in $POST['name']).
Hence, $_POST['search'] is empty, and your SQL request is :
select * from test where name LIKE '%%' LIMIT 0 , 10
Which returns all results.
You should replace your data line in your AJAX call to :
data:"search="+name,
Related
Everthing is working I've tested it, my only problem is that how to transfer into Codeigniter.. please someone help and explain if can.. I have to add this on my school project but in Codeigniter framework. I'm newbie on Codeigniter and I want to learn more.
This is my "print.php"
<?php
require('fpdf/fpdf.php');
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost", "root", "", "datedate");
$output = '';
$query = "SELECT * FROM tbl_order WHERE order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."' ";
$result = mysqli_query($connect, $query);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','',10);
$pdf->Cell(50,10,'Date:'.date('d-m-Y').'',0,"R");
$pdf->Ln(15);
$pdf->SetFont('Arial','B',16);
$pdf->Cell(0,10,'USERS',1,1,"C");
$pdf->SetFont('Arial','B',12);
$pdf->Cell(10,8,'No.',1);
$pdf->Cell(45,8,'First Name',1);
$pdf->Cell(45,8,'Middle Name',1);
$pdf->Cell(45,8,'Last Name',1);
$pdf->Cell(45,8,'Birth Date',1);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result)){
$no=$no+1;
$pdf->Ln(8);
$pdf->SetFont('Arial','',12);
$pdf->Cell(10,8,$no,1);
$pdf->Cell(45,8,$row['order_customer_name'],1);
$pdf->Cell(45,8,$row['order_item'],1,0,"C");
$pdf->Cell(45,8,$row['order_value'],1);
$pdf->Cell(45,8,$row['order_date'],1);
}
}
}
$pdf->Output();
?>
this is my "index.php"
<?php
$connect = mysqli_connect("localhost", "root", "", "datedate");
$query = "SELECT * FROM tbl_order ORDER BY order_id asc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Ajax PHP MySQL Date Range Search using jQuery DatePicker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">Ajax PHP MySQL Date Range Search using jQuery DatePicker</h2>
<h3 align="center">Order Data</h3><br />
<div class="col-md-3">
<input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" />
</div>
<div class="col-md-3">
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" />
</div>
<div class="col-md-5">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />
</div>
<div style="clear:both"></div>
<br />
<div id="order_table">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["order_id"]; ?></td>
<td><?php echo $row["order_customer_name"]; ?></td>
<td><?php echo $row["order_item"]; ?></td>
<td>$ <?php echo $row["order_value"]; ?></td>
<td><?php echo $row["order_date"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"print.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
I think your code is currently in pure PHP, and you want to code it in CodeIgniter, right?
If so, please take a look at it's document. Or sample here: This link
I suggest your code will like this:
In models/order.php
Class Order {
public function detail($id) {
// Get and return your data here
}
}
In controllers/index.php
Class IndexController {
public function index() {
// load model here
$data = ... // call to Order->detail
// Return view here
}
}
In views/index.php
// Render your view, form here
In controllers/print.php
Class Print {
public function index() {
// Do your code after submit here
}
}
Hope this can help you.
Trying to solve my problem with deleting rows from generated table.I have a page called report.php that shows all the rows from database and there is option 'delete row'. My problem is when I click on delete nothing happens and it should go on delete.php file. For now couldnt solve this by myself, maybe you see something that I dont. I dont get any errors so I am a little bit confused. Thank you.
report.php
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<head>
<body>
<?php
require_once '../include/functions.php';
require_once '../include/db.php';
$htmltable = "";
$htmltable .= "<table>
<tr>
<th>ID</th>
<th>Ime</th>
<th>Ime slavljenika</th>
<th>Datum</th>
<th>Poruka</th>
<th>Vreme prijave</th>
<th>Obrisi</th>
</tr>";
$prep = $db->prepare("SELECT * from prijavljeni");
$prep->execute();
$prijavljeni = $prep->fetchAll();
foreach($prijavljeni as $prijavljen => $row) {
$htmltable.= '<tr>
<td>'.$row['prijavljeni_id'].'</td>
<td>'.$row['ime'].' </td>
<td>'.$row['ime_slavljenika'].' </td>
<td>'.$row['datum'] .'</td>
<td>'.$row['poruka'].' </td>
<td>'.$row['vreme'].'</td>
<td><a href="delete.php?prijavljeni_id=<?php echo $prijavljeni["prijavljeni_id"]; ?>Delete</a></td>
</tr>';
}
$htmltable.='</table>';
echo $htmltable;
?>
<div>
<button onclick="return email()">Posalji</button>
<div id="emailporuka">
</div><br><br>
</div>
<p align="center">Logout</p>
<script>
function email(){
$.ajax({
type:"post",
url: "email.php",
success: function(data){
//window.alert(data);
document.getElementById("emailporuka").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
</body>
</html>
delete.php
<?php
include('../include/db.php');
$prijavljeni_id=$_GET['prijavljeni_id'];
$result = $db->prepare("DELETE FROM prijavljeni WHERE prijavljeni_id= :prijavljeni_id");
$result->bindParam(':prijavljeni_id', $prijavljeni_id);
$result->execute();
header("location: izvestaj.php");
?>
You just need to change this in your $htmltable. (there was an error in appending strings in last block).
$htmltable.= '<tr>
<td>'.$row['prijavljeni_id'].'</td>
<td>'.$row['ime'].' </td>
<td>'.$row['ime_slavljenika'].' </td>
<td>'.$row['datum'] .'</td>
<td>'.$row['poruka'].' </td>
<td>'.$row['vreme'].'</td>
<td>Delete</td>
</tr>';
Update your code
$result->bindParam(':prijavljeni_id', $prijavljeni_id);
To
$result->bindParam('prijavljeni_id', $prijavljeni_id);
Remember one thing always avoid : before on bindParam method but we using : on prepareQuery to indicate replaceable value.
Please help me. Thanks in advance. Actually I am trying to insert selected checkbox rows into database using jquery but i don't know how to insert into DB.My jquery code is selecting the row but how to check whether the row is passing through ajax request. My table has a dynamic row from the database table with checkboxes. so when i checked the checkboxes and click the submit button then the table row should insert into the database table.
My code as below:
test.php
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Could not connect:".mysql_error());
}
mysql_select_db("cakephp",$con);
$sql = mysql_query("select * from carts where userid=13");
?>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script src="jquery.validate.min.js"></script>
<script src="jquery-ui.min.js"></script>
<style type="text/css">
.row_selected {background-color: #BFCBD7;}
</style>
<script>
$(document).ready(function(){
$('.chk').on('change', function() {
//alert('Hai');
var thisCheckbox = $(this);
var thisRow = thisCheckbox.closest('tr');
if ( thisCheckbox.is(':checked') ) {
thisRow.addClass('row_selected');
} else {
thisRow.removeClass('row_selected');
};
});
$('#orderSave').on('click', function(row,tr) {
//e.preventDefault();
//var toPost = $('.row_selected input').serialize();
/* Now post and insert into database */
//$.post('/invl_exams/ordercompletion', toPost, function(data) {
//alert('Success!');
//});
// Here i am creating the array to hold each selected row
var TableData = new Array();
var priVal = $(tr).find('td:eq(6)').text();
var priceVal = priVal.replace('$','');
TableData[row] = {
//column names: corresponding row data
"userid" : $('#userid').val(),
"username" : $('#hiddenUser').val(),
"date" : $(tr).find('td:eq(3)').text(),
"exam" : $(tr).find('td:eq(4)').text(),
"venue" : $(tr).find('td:eq(5)').text(),
"price" : priceVal,
"total_orders" : $(tr).find('td:eq(7)').text(),
"amount" : $(tr).find('td:eq(8)').text(),
"orders_completion" : $(tr).find('td:eq(9)').text()
}
TableData = JSON.stringify(TableData);
//console.log(TableData);
$.ajax({
type : "POST",
url : "testsubmit.php",
cache : "false",
data : {data:TableData},
success : function(result){
console.log(result);
}
});
});
});
</script>
</head>
<body>
<table border="1">
<tr>
<th>S.No</th>
<th>Exam Name</th>
<th>Venue</th>
<th>Date</th>
<th>Price</th>
<th>No of Orders</th>
<th>Amount</th>
<th>Checks</th>
</tr>
<?php
$i=1;
while($row = mysql_fetch_array($sql))
{
?>
<tr>
<td><?php echo $i++;?></td>
<td style="display:none" id="userid">13</td>
<td style="display:none" id="hiddenUser">Gautham</td>
<td><?php echo $row['exam_name'];?></td>
<td><?php echo $row['venue'];?></td>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['price'];?></td>
<td><?php echo $row['noOf_orders'];?></td>
<td><?php echo $row['amount'];?></td>
<td><input type="checkbox" name="chk" class="chk" value="1"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="7"> </td>
<td><button type="button" class="btn btn-success btn-xs" id="orderSave">Submit</button></td>
</tr>
</table>
</body>
</html>
testsubmit.php ( In this file i was checking the post request using print_r($_POST) )
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Could not connect:".mysql_error());
}
mysql_select_db("cakephp",$con);
//if(isset($_POST['toPost']))
//{
print_r($_POST);
//}
?>
your data inside last td is an input so you must
change from
"orders_completion" : $(tr).find('td:eq(9)').text()
to
"orders_completion" : $(tr).find('.chk')[0].checked
I am currently working on a project that shows data from an SQL table using bootstrap editable for live editing.
It works fine - changes are transferred to the SQL table. What is already working?:
Showing current value from SQL table
Providing a drop-down for selection
Transferring changed values to SQL table
-> BUT Part 3 (transferring changed value) is only working for free-text input (class xedit).
What I am looking for is the code for: transferring chosen value of drop-down-list to SQL-Table
Here is the HTML-code:
<?php
include("connect.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta charset="utf-8">
<link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="assets/css/custom.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div style="text-align:center;width:100%;font-size:24px;margin-bottom:20px;color: #2875BB;">EDIT YOUR CHARACTERS</div>
<div class="row">
<table class= "table table-striped table-bordered table-hover">
<thead>
<tr>
<th colspan="1" rowspan="1" style="width: 180px;" tabindex="0">NAME</th>
<th colspan="1" rowspan="1" style="width: 220px;" tabindex="0">ROLE</th>
<th colspan="1" rowspan="1" style="width: 288px;" tabindex="0">SECOND ROLE</th>
</tr>
</thead>
<tbody>
<?php
$query = mysql_query("SELECT * FROM characters");
$i=0;
while($fetch = mysql_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td class="xedit" id="'.$fetch['id'].'" key="name">'.$fetch['name'].'</td>
<td class="xedit" id="'.$fetch['id'].'" key="role">'.$fetch['role'].'</td>
<td class="xedit2" id="'.$fetch['id'].'" key="secondrole">'.$fetch['secondrole'].' </td>
</td>
</tr>';
}
?>
</tbody>
</table>
</div>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/bootstrap-editable.js" type="text/javascript"></script>
<script>
$(function(){
$('.rolestatus').editable({
source: [
{value: 1, text: 'DD'},
{value: 2, text: 'HEAL'},
{value: 3, text: 'TANK'}
]
});
});
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var key = $(this).closest('.editable-container').prev().attr('key');
var x = $(this).closest('.editable-container').prev().attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('.editable-container').prev().text(y);
$.ajax({
url: "process.php?id="+x+"&data="+y+'&key='+key,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
</div>
</body>
</html>
Here is the process.php code
<?php
include("connect.php");
if($_GET['id'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
if(mysql_query("update characters set $key='$data' where id='$id'"))
echo 'success';
}
?>
So does anybody know how I can transfer the chosen dropdown-value (class -> xedit2) to SQL table?
Hope you can help!
Not sure exacly how x-editable works
But in first look i think that the type of your ajax should be "POST" if you want to update some data. And in my opinion you have syntax error in your sql query near "$key"
I have a form which contains a dropdown box, when the value is changed the form uses jQuery and ajax to produce a table. The table contains data based on the value of the dropdown box and also links.
My initial script which is where the dropdown box is and where the table is added is:
<?php require_once('/connections/db.php');
mysql_select_db($database_db, $db);
$query_weeks = "SELECT WeekNo, WeekName FROM tbl_weeks ORDER BY WeekNo ASC";
$weeks = mysql_query($query_weeks, $db) or die(mysql_error());
$row_weeks = mysql_fetch_assoc($weeks);
$totalRows_weeks = mysql_num_rows($weeks);
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form name="form1" method="post" action="">
<select id="weekselect" name="week">
<?php
do {
?>
<option value="<?php echo $row_weeks['WeekNo']?>"><?php echo $row_weeks['WeekName']?></option>
<?php
} while ($row_weeks = mysql_fetch_assoc($weeks));
$rows = mysql_num_rows($weeks);
if($rows > 0) {
mysql_data_seek($weeks, 0);
$row_weeks = mysql_fetch_assoc($weeks);
}
?>
</select>
</form>
<div id="mydata"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
// listen to change in monthselect
$('#weekselect').change(function(){
var week= $('#weekselect option:selected').val();
//pass val to php
$.post('test2.php',{week: week}, function(data) {
//do something with the data
$('div#mydata').html(data);
});
});
});
</script>
</body>
</html>
The script produces the dropdown from the mysql db and creates a listener for it, when the select is changed the value of the select is passed to the test2.php using jquery. the data returned is added to div #mydata
Test2 which produces the table is as follows
<?php
if (!isset($_SESSION)) {session_start();}
include('session.php');
require_once('Connections/dbc.php');
$open_week=$_SESSION['MM_OpenWeek'];
$week_selected=$_POST['week'];
$season=$_SESSION['MM_Season'];
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
echo '<p>Week selected: '.$week_selected .'<p>';
echo '<p>Open Week: '.$open_week .'<p>';
if ($week_selected>=$open_week) {
echo '<p>Week Open<p>';
} else {
echo '<p>Week Closed<p>';
}
//create recordset of fixtures for the week selected
$sql="SELECT * FROM q_games_stats WHERE WeekNo =".$week_selected . " and Season=". $season ." and at='Home' ORDER BY WeekNo ASC";
$rec_games=mysqli_query($dbc,$sql);
//create table using the recordset
?>
<div id="data_table">
<table class="table" align="center">
<th class="th" width="80px">Match Date</th>
<th class="th" width="150px">Home Team</th>
<th class="th" width="40px">Score</th>
<th class="th" width="150px">Away Team</th>
<th class="th" width="150px">Link</th>
<?php
while ($row=mysqli_fetch_array($rec_games))
{
?>
<tr class="tr">
<td class="td"><?php echo $row['MatchDate']?></td>
<td class="td"><?php echo $row['TeamName']?></td>
<td class="td"><?php echo $row['Score']?></td>
<td class="td"><?php echo $row['OppName']?></td>
<td class="td">Link</td>
</tr>
<?php
}
?>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
// listen to change in monthselect
$('#data_table a').click(function(){
alert("link clicked");
});
});
</script>
</body>
</html>
This produces the table, which includes links. There is an event listener of the links in the table, which when I click produces an alert.
What I want to do is instead of an alert being produced when clicking a link is for the table to reproduce, the reason for this is when the user clicks a link it will run a script which will change the underlying data in the table and therefore the table will need to be refreshed.
Is there I way I can do this, or is there a better way to do what I want to do?