I'm working on a live search in AJAX (for a database of powder horns) with two inputs, the first for the year, and the second for the conflict. The problem I'm having is when one of the inputs is blank, it only returns elements in the table that have no date or conflict name listed. Instead I want blank inputs to behave as null, and show everything from the table. I can fix the date section using a conditional to check if (!$date), but I can't get the select input to behave the same way if the user chooses blank again.
Any ideas on how to fix this? Especially in one query without a ton of PHP if/else?
HTML
<h1> Powder Horn Search Engine </h1>
Date <input id="date" type="text" name="variable">
To <select id="conflict">
<option> </option>
<option value="French & Indian War">French & Indian War</option>
<option value="Revolutionary War">Revolutionary War</option>
<option value="War of 1812">War of 1812</option>
</select>
<div id="result">
</div>
Javascript
var date="";
var conflict=""
$(document).ready( function () {
//Send date to PHP
$("#date").keyup(function(){
date = $("#date").val();
conflict=$("#conflict").val();
$.ajax({
type: "POST",
data: {date: date, conflict:conflict},
url: "powderhornsearch.php",
success: function(data){ //response param
$("#result").html(data);
}
});
});
//Send conflict to PHP
$("#conflict").change(function(){
conflict=$("#conflict").val();
date = $("#date").val();
$.ajax({
type: "POST",
data: {conflict: conflict, date:date},
url: "powderhornsearch.php",
success: function(data){ //response param
$("#result").html(data);
}
});
});
});
PHP
$date = $_POST['date'];
$conflict=$_POST['conflict'];
$result = mysql_query ("SELECT * FROM powderhorns WHERE Date LIKE $date AND Conflict LIKE '$conflict' ", $connection);
if (!$result) {
die("Database query failed:" . mysql_error());
}
echo "<table>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>".
"<td>".$row[1]."</td>".
"<td>".$row[2]."</td>".
"<td>".$row[3]."</td>".
"<td>".$row[4]."</td>";
echo "</tr>";
}
echo "</table>";
EDIT
I changed the value of the blank select to "1" because it seemed like MySQL was having trouble with the empty string. I got everything to work by using the following code. As I am new to programming, if anyone has a suggestion on how to make it more condensed or elegant, I'd love your ideas. Thanks so much!
if (!$date) {
$date="";
}
if ($conflict=="1" && !$date)
{
$result = mysql_query ("SELECT * FROM powderhorns", $connection);
}
else if ($conflict==1){
$result = mysql_query ("SELECT * FROM powderhorns WHERE Date LIKE $date ", $connection);
}
else if (!$date && $conflict){
$result = mysql_query ("SELECT * FROM powderhorns WHERE Conflict LIKE '$conflict' ", $connection);
}
else{
$result = mysql_query ("SELECT * FROM powderhorns WHERE Conflict LIKE '$conflict' and Date LIKE $date ", $connection);
}
change it to:
$condition=1;
if(trim($date)) $condition .=" and Date LIKE '$date'";
if(trim($conflict)) $condition .=" and Conflict LIKE '$conflict'";
$result = mysql_query ("SELECT * FROM powderhorns WHERE $condition ", $connection);
Related
I'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research
Having trouble pulling variables from one PHP to another script.
I have three different files, adminPage.html, reportScript.php, and report.php.
adminPage.html takes variables from the user and uses AJAX post function to post the variables to reportScript.php.
report.php is supposed to pull those posted variables from reportScript.php and use the variables in a SQL function, however, I am receiving an error stating that I have an "undefined index: startDate" and "undefined index: endDate" where I am instantiating the variables in PHP.
adminPage.html:
<center><h2> Choose the dates below that you need an order list from: </h2>
</br>
<form>
<h2>Start:</h2>
<input type="date" id ="reportStartDate" name = "startDate">
</br>
<h2>End:</h2>
<input type="date" id ="reportEndDate" name = "endDate">
</form>
</center>
</br></br>
<button id="runReportButton" onclick = "runReport()"> Run Report </button>
<script>
function runReport()
{
var jStartDate;
var jEndDate;
jStartDate = document.getElementById("reportStartDate").value;
jEndDate = document.getElementById("reportEndDate").value;
/*console.log(jStartDate);
console.log(jEndDate); */
$.ajax
({
type: "POST",
url: "phpScripts/reportScript.php",
data: {startDate: jStartDate, endDate: jEndDate},
success: function(response)
{
console.log("posted");
window.open("report.php", "_self");
}
});
}
</script>
reportScript.php:
<?php
require 'connect.php';
//posts data to db
$startDate = $_POST["startDate"];
$endDate = $_POST["endDate"];
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < startDate OR
dateOrdered > endDate)";
$result = $conn->query($sql);
if($result){
echo "true";
}
else{
echo "false";
}
?>
report.php:
<?php
require 'phpScripts/connect.php';
require 'phpScripts/reportScript.php';
//posts data to db
/*$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];*/
/*$startDate = '2018-01-01';
$endDate = '2018-08-08'; */
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < '$startDate' OR dateOrdered > '$endDate');";
$result = $conn->query($sql);
//above is reportScript.php, below is pulling list method from order.php
//below works, just needs variables from the reportScript
echo "<ul>";
if($result->num_rows >0)
{
$i = 0;
while($row = $result->fetch_assoc()) // this loads database into list, also
creates array of pricing which someone can pull from later to get total
{
echo "<li style='font-size:15px'>".$row["drinkName"]. ", Date Ordered: "
.$row["dateOrdered"] . ",Cost: " .$row["drinkCost"] . "</li>";
echo "</br>";
$i = $i+1;
}
}else {
echo "<p> you're a dummy and you did this wrong </p>";
}
echo "</ol>";
?>
You forgot the dollar sign ($) in your variables in reportScript.php.
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < $startDate OR
dateOrdered > $endDate)";
This statement is also vulnerable to sql injection.
With some of the advice taken from #Ralf, I combined both reportScript.php and report.php, and used a $_GET statement to put the date variables into the URL upon opening. This way, the query isn't placed twice and the variables are still saved.
Hi I need to populate a dropdown field using a value taken from the database and show it as selected and at the same i would like to show a list of options taken from the database,
Everything works fine except for the field "User Group" this is what i've done so far, can anybody please help me?
Many thanks
Html file
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">User Group
<span class="required"> * </span>
</label>
<select class="form-control bs-select" id="userGroup" name="userPippo">
<?php
$select_group_query="SELECT group_id, group_name FROM user_group";
$run= mysqli_query($conn, $select_group_query);
while($row= mysqli_fetch_array($run)) {
echo "<option value= '".$row['group_id']."' >" . $row['group_name'] . "</option>";
}
?>
</select>
</div>
</div>
</div>
Javascript file
function GetUserDetail(id) {
$("#EditUserModal").modal("show");
$("#user_id").val(id);
var user_id = $('#user_id').val();
$.ajax({
url: "../controllers/ctrl_admin_user_app/ctrl_admin_get_user_details.php",
method: "POST",
data: {
user_id: user_id
},
dataType: "json",
success: function(data) {
console.log(data);
$('#firstName').val(data.user_first);
$('#lastName').val(data.user_last);
$('#userEmail').val(data.user_email);
$('#userTel').val(data.user_telephone);
$('#userFiscalcode').val(data.user_fiscalcode);
$('#userBirth').val(moment(data.user_birth).format('DD/MM/YYYY'));
$('#userDocument').val(data.user_iddocument);
$('#userRole').val(data.user_role);
// ricarico il campo per falo funzionare con il plugin bs-select
$('#userRole').selectpicker('refresh');
$('#userGroup').val(data.group_name); // doesn't work
// make it work with bs-select
$('#userGroup').selectpicker('refresh');
doesn 't work
$("#EditUserModal").modal("show");
}
});
}
PHP File
if (isset($_POST["user_id"])) {
$userid = $_POST['user_id'];
$user_id = filter_var($userid, FILTER_SANITIZE_NUMBER_INT);
$query = "SELECT group_id, group_name, user_first, user_last, user_email, user_telephone, user_fiscalcode, user_birth, user_iddocument, user_role FROM user_group_join LEFT JOIN (user_group, users) ON (user_group_join . group_join_id = user_group . group_id AND user_group_join . user_join_id = users . user_id) WHERE user_join_id = ? ";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$response = array();
while ($row = mysqli_fetch_assoc($result)) {
$response = $row;
}
echo json_encode($response);
}
from the Documentation,
.selectpicker('val');
You can set the selected value by calling the val method on the element.
$('.selectpicker').selectpicker('val', 'Mustard');
$('.selectpicker').selectpicker('val', ['Mustard','Relish']);
This is different to calling val() directly on the select element. If you call val() on the element directly, the bootstrap-select ui will not refresh (as the change event only fires from user interaction). You will have to call the ui refresh method yourself.
.selectpicker('refresh');
To programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.
$('.selectpicker').selectpicker('refresh');
So,
Replace these lines
$('#userGroup').val(data.group_name); // doesn't work
// make it work with bs-select
$('#userGroup').selectpicker('refresh');
with this line,
$('#userGroup').selectpicker('val', data.group_id).selectpicker('refresh');
I am having trouble executing SQL via AJAX when a dropdown box is changed and would like some help if possible.
Background Info
I have been tasked with creating a daily calendar that shows all the classes ran at a gym, which at its maximum is 5 x classes of 6 (30) people per hour for 14 hours.I'm no pro and I may have created a convoluted way around this issue, please let me know if i have.
I have managed to create the view which consists of 14 columns of 30 drop down boxes (5 x classes of 6 per hour for 14 hours). Each drop down box polls the db and if an entry resides it will populate the box with the name of the bookinguser. If no booking is found it will create a drop downbox that polls the members table and presents all the members of the gym, which when changed, will hopefully book that person in. - herein lies my current issue!
Each drop down box's name corresponds to the time, group and headcount which I intend on passing to javascript function and eventually to the SQL statement. Each option's value corresponds with the memberid which will also be passed giving all the information needed to construct the SQL.
The code I have so far
HTML - snipped generated from php loops
<div id="results">
<div id="07" class="column">07:00<br/>
<div id="group1">
<select name="07:00-1-0" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
<select name="07:00-1-1" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
PHP
<?php
$mysqli = new mysqli("localhost", "root", "", "gym");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
function hyphenate($str) {
return implode("-", str_split($str, 2));
}
function getmembers($time,$group,$iteration)
{
$date=$_GET["date"];
$date=hyphenate($date);
$date = explode('-', $date);
$new_date = $date[2].'-'.$date[1].'-'.$date[0];
$mysqli = new mysqli("localhost", "root", "", "gym");
if ($iteration == 0){
$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1");
}
else {$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1,$iteration");
}
$rowcount=mysqli_num_rows($result);
if ($rowcount==$iteration && $iteration == 0)
{
$result = $mysqli->query("select firstname, lastname,memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
else if ($rowcount>=$iteration){
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)">';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option><option value="cancel">Cancel</option>';
}
echo "</select>";
}
else{
$result = $mysqli->query("select firstname, lastname, memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
}
?>
JS
function getda(id,booking){
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:id
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
}
samefile.php
<?php
if(isset($_POST['get_option']))
{
inlude 'config/config.php';
$name=$_POST["get_option"];
echo "<SCRIPT>
alert('$name');
</SCRIPT>";
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
$mysqli->close();
?>
The console in chrome looks fine (below) but no records are inserted and the php alert doesn't show. I havent passed any of the variable to the SQL as I was first testing that a query executed properly
jquery.min.js:4 XHR finished loading: POST "http://localhost/gym/samefile.php".send # jquery.min.js:4n.extend.ajax # jquery.min.js:4getda # cal.php?date=140416:42onchange # cal.php?date=140416:36ListPicker._handleMouseUp # about:blank:535
Might want to look into jQuery's .change(). I think that it would work with something like below for your code. You could also have it call your function that has ajax in it as well
$( ".class" ).change(function() { //can use #id here too
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:this.value
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
});
I see three problems in samefile.php - include spelled incorrectly, an extra semicolon, and a missing closing bracket:
<?php
if(isset($_POST['get_option']))
{
include 'config/config.php';
$name = $_POST["get_option"];
//this should be converted to parameterized queries
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
if(is_object($query)){
echo 'successfully inserted';
} else {
echo 'insert failed';
}
$mysqli->close();
} else {
echo 'no data to process!';
}
?>
Using a few answers on here I have got row being added to MySQL upon a button press but the data is blank and so I can only assume the variables are not being passed.
I really don't know what I am doing wrong, any help would be greatly appreciated.
PHP
<? $sql = "SELECT itemname FROM items ORDER BY itemname ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<button onclick='javascript:ajaxCall(" . $row['id'] . ")'><span class='btn-text'>" . $row['itemname'] . "</span></button>";
}
?>
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function ajaxCall(id){
$.ajax({
type: "POST",
url: "additem.php",
success: function(data){
// callback function
}
});
return false;
}
</script>
additem.php
// Connect database.
include("settings.php");
mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name);
$id = $_POST['id'];
$itemsearch = mysql_query("SELECT itemname, itemcategory, price, qty FROM presales WHERE id='$id'");
$itemsearchrest = mysql_num_rows($itemsearch);
$itemname = $itemsearchrest['itemname'];
$itemcategory = $itemsearchrest['itemcategory'];
$price = $itemsearchrest['price'];
$qty = $itemsearchrest['qty'];
$sql = "INSERT INTO presales (itemname, itemcategory, price, qty) VALUES('$itemname', '$itemcategory', '$price', '0')";
if(mysql_query($sql)){
return "success!";
}
else {
return "failed!";
}
?>
mysql_num_rows returns the number of rows. It's not an array. Use fetch_assoc or similiar.
See sample in the PHP documentation!
Also your AJAX call is missing the data:
$.ajax({
type: "POST",
url: "additem.php",
data: {
id: id
}
});
Please switch to PDO or MySQLi. MySQLi will use the same function names but it is object orientated. PDO will name the functions slightly different but basically work the same way.