getting a text value populated by a select option - php

i am in dire need here. i have gone to every person i know that knows php/mysql/ajax, but no one can help.
i am trying to get an input field populated with data from my dbase that is chosen from two different selects. here is the situation:
building a golf scoring page on my website. the user will choose a course (select #1), then the tee they played (select #2), which then the disabled text inputs will populate with the rating and slope. the rating and slope are very important b/c they help figure out the handicap for the user. i am able to get everything to populate fine, but i can't figure out the correct WHERE clause in my query on the get_rating.php page. can somebody help me with that query?
here is my code:
dbase setup:
this is pulling from 2 tables, one is the courses table (course_id, c_id, name) and the other is the course_tees table (tee_id, course_name, c_id, t_id, color, rating, slope). the c_id's on both tables are the same.
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class='new_score'>
<div class='form-group'>
<select class="form-control" name="course_name" onchange="get_tees(this.value)">
<option value="">select a tee</option>
<?php get_courses() ?>
</select>
</div>
<div class='form-group'>
<select class='form-control' name='tee_played' onchange="get_rating(this.value)" id='txtHint'>
<option value="">select a tee</option>
</select>
</div>
<div class="form-group" id="getRating">
</div>
the first select uses the get_tees.php code (listed below) and the second one uses the get_rating.php code (listed 2 below) which is the one i'm having trouble with.
get_tees.php
$con = mysqli_connect("***","***","***","***") or die("connection was not established");
$q = intval($_GET['q']);
mysqli_select_db($con,"course_tess");
$sql="SELECT * FROM course_tees WHERE c_id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result)) {
$tee_id = $row['tee_id'];
$c_id = $row['c_id'];
$t_id = $row['t_id'];
$tee_color = $row['color'];
$cor_rating = $row['rating'];
$cor_slope = $row['slope']; ?>
<option value='<?php echo $tee_id ?>'><?php echo $tee_color ?></option>
get_rating.php
$con = mysqli_connect("***","***","***","***") or die("connection was not established");
$q = intval($_GET['q']);
mysqli_select_db($con,"course_tees");
$sql="SELECT * FROM course_tees";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result)) {
$c_id = $row['c_id'];
$t_id = $row['t_id'];
$cor_rating = $row['rating'];
$cor_slope = $row['slope']; ?>
<input type='text' name='cor_rating' class='form-control' value='<?php echo $row['rating']; ?>' disabled>
<input type='text' name='cor_slope' class='form-control' value='<?php echo $row['slope']; ?>' disabled>
and here's my ajax for both selects:
function get_tees(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_tees.php?q="+str,true);
xmlhttp.send();
}
}
function get_rating(str) {
if (str == "") {
document.getElementById("getRating").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("getRating").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_rating.php?q="+str,true);
xmlhttp.send();
}
}
am i not passing something correctly in my ajax? what am i doing wrong?!?! PLEASE help!!

#chris85 this is essentially the bandaid that i have put over the issue for right now ... instead of trying to populate the text fields automatically, i am listing them in the selects and manually putting in the rating/slope ... this is my code:
php:
mysqli_select_db($con,"course_tess");
$sql="SELECT * FROM course_tees WHERE c_id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<option value=''>select a tee</option>";
while($row=mysqli_fetch_array($result)) {
$tee_id = $row['tee_id'];
$c_id = $row['c_id'];
$t_id = $row['t_id'];
$tee_color = $row['color'];
$cor_rating = $row['rating'];
$cor_slope = $row['slope']; ?>
<option value='<?php echo $tee_color ?>'><?php echo $tee_color ?> - <?php echo $cor_rating ?> : <?php echo $cor_slope ?></option>
and the form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class='new_score'>
<div class='form-group'>
<select class="form-control" name="course_name" onchange="get_tees(this.value)">
<option value="">select a tee</option>
<?php get_courses() ?>
</select>
</div>
<div class='form-group'>
<select class='form-control' name='tee_played' onchange="get_rating(this.value)" id='txtHint'>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control" name="cor_rating" placeholder="enter rating from above">
<input type="text" class="form-control" name="cor_slope" placeholder="enter slope from above">
</div>
so, like you can see, it's just a bandaid. if you want to see it working, go to the http://www.havikmarketing.com and sign in with these credentials:
EM: test#test.com
PW: testing123
then go up to the settings (gears) and choose 'new round'. go through and enter a score ... you'll see how it pulls everything through. now mind you, i just have it set up as pretty much a skeleton right now ... so no judging on the design :)
thanks again

Related

Create a Chain of drop-down list that base on the input of the previous one form the database in php

i am using database to populate the dorpdown lis. now when i select the option from the first dynamic populated drom down list i want to use it to populate another dropdown list and based on that selection third dromdown list.
Here's the code i am working on,
<html>
<?php
include './config.php';
?>
<head>
<meta charset="UTF-8">
<title></title>
<SCRIPT>
$(".dropdown").hide();
$("#testcasedata").on("change", function() {
$(".dropdown").hide();
var value = $("#testcasedata").val();
$("#dropdown" + value).show();
});
</script>
</head>
<body>
<form method="POST" action="createTestCase.php">
// This is the first dropdown list
// It will return testsuite_id in dropdownlist
<?php
$sqll="SELECT testsuite_id FROM assigned_testsuite_tester Where Tester_name = 'Pritesh'";
echo "<select class='form-control' name='testsuite'>";
echo "<option value=''>Select One</option>";
foreach ($conn->query($sqll) as $row){
echo '<option value="'.$row['testsuite_id'].'">'.$row['testsuite_id'].'</option>';
}
echo "</select>";
?>
<input type="submit" name="submit" />
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//testsuite_id will be the input variable for the second dropdownlist
// the second dropdown list will populate with testcase_id.
$testsuite = filter_input(INPUT_POST, 'testsuite');
echo $testsuite;
if($testsuite != ''){
$sqll="SELECT Testcase_id FROM assigned_testsuite_testcase Where testsuite_id = '$testsuite'";
echo "<select name='testcasedata' id='testcasedata' >";
echo "<option value=''>Select One</option>";
foreach ($conn->query($sqll) as $row){
echo '<option value="'.$row['Testcase_id'].'">'.$row['Testcase_id'].'</option>';
}
echo "</select>";
}
// with use of test case id i am retrieving the Product_id
$testcase = filter_input(INPUT_POST, 'testcase');
$sqll="SELECT Product_id FROM Testcase_master Where Testcase_id = '$testcase'";
$productid='';
foreach ($conn->query($sqll) as $row){
$productid = $row['Product_id'];
}
//now product id must be the input for the third dropdownlist.
if($productid != ''){
$sqll="SELECT circle.circle_id,circle.Circle_name FROM circle INNER JOIN assigned_circle_product ON assigned_circle_product.`Product_id` = '$productid'";
echo "<select class='dropdown' name='circledata' id='circledata'>";
echo "<option value=''>Select One</option>";
foreach ($conn->query($sqll) as $row){
echo '<option value="'.$row['Circle_id'].'">'.$row['Circle_name'].'</option>';
}
echo "</select>";
}
}
?>
</body>
i was able to populate the first drop-down list and based on that populate the second drop-down list.but having problem for populating third one.
I was browsing through similar questions and find out that i need to use jquery/JavaScript to do that.I don't know that much about jquery but have inserted code for that too but still having problem to populating the third drop down list.
I am stuck at this point.Please give me some guidance.
I have been learning Javascript/Jquery and this is what i have done.
I don't know if it's a correct way or not. please look and tell me if i can do more to improve code.
First i have devided whole program into three seprate PHP files.
1.Main PHP File
<!DOCTYPE html>
<html>
<?php
include 'header.php';
include 'footer.php';
include './config.php';
?>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
function showCircle(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","GetProduct.php?q="+str,true);
xmlhttp.send();
}
function product1(str) {
str1 = document.getElementById("project");
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","GetTestcase.php?prod="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Add Circle to Product</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Select the circles where you want your product to test:
</div>
<div class="panel-body">
<div class="dataTable_wrapper">
<form action="circlrproduct.php" method="GET">
<div class="col-lg-6">
<div class="form-group">
<label>Project Name</label>
<?php
$sqll="SELECT Project_id,Project_title FROM project_master";
echo "<select class='form-control' name='project' onchange='showCircle(this.value)'>";
echo "<option value=''>Select One</option>";
foreach ($conn->query($sqll) as $row){
echo "<option value=$row[Project_id]>$row[Project_title]</option>";
}
echo "</select>";
?>
</div>
<div class="form-group">
<div id="txtHint"></div>
<!--<div id="txtHint1"></div>-->
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="submit" value="submit">Submit</button>
<button type="reset" class="btn btn-primary">Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
First i select the project from the drop down list and at at the time of selection a ajax call will be made to get the product.
GetProduct.php
if(isset($_GET['q'])){
$q = (string)filter_input(INPUT_GET,'q');
}else{
// header('Location:AddCircleToProduct.php');
}
$sql2="SELECT Product_id,Product_title FROM product_master where Project_id = '$q'";
$support = $q;
$result = $conn -> query($sql2);
echo "<label>Product Name</label>";
echo "<select class='form-control' name='product' onchange='product1(this.value)'>";
echo "<option value=''>Select One</option>";
while ($row = mysqli_fetch_array($result)){
echo "<option value={$row['Product_id']}>{$row['Product_title']}</option>";
}
echo "</select>";
At the time of product selection one another call is made through Ajax to get the test case.
3.GET Test case
if(isset($_GET['prod'])){
$product = filter_input(INPUT_GET, 'prod');
$query = "select * from testcase_master where Product_id = '$product'";
//echo $query;
echo '<div class="panel-body"><div class="dataTable_wrapper"><table class="table table-striped table-bordered table-hover" id="dataTables-example"">';
echo '<thead><tr><th>SELECT</th><th>Testcase Id</th><th>Testcase Title</th><th>Description</th><th>Created by</th><th>Subscriber Type</th><th>Priority</th></tr></thead><tbody>';
if($results = $conn -> query($query) or die(mysqli_errno($conn))){
while ($row = mysqli_fetch_array($results)) {
echo '<tr class="odd gradeX">';
echo "<td><input type=\"checkbox\" name=\"checkbox[]\" id=\"checkbox[]\" value=\"".$row['Testcase_id']."\" class='form-control'/></td>";
echo "<td>{$row['Testcase_id']}</td><td>{$row['Testcase_title']}</td><td>{$row['Testcase_desc']}</td><td>{$row['Created_by']}</td><td>{$row['Subscriber_type']}</td><td>{$row['Priority']}</td>";
echo '</tr>';
}
echo '</tbody></table></div></div>';
} else {
echo 'ss' . mysqli_error($conn);
}
}
else{
echo'Sorry You cant access this page Directly.';
}
?>
After getting the list of test case selection of checkbox is made.
4.circledata.php
<?php
include './config.php';
if(isset($_GET['submit'])){
if(isset($_GET['checkbox'])){
if (is_array($_GET['checkbox'])) {
foreach($_GET['checkbox'] as $value){
$q1 = "INSERT INTO tmtool.assigned_circle_product (`Circle_id`, `Product_id`) VALUES ('.$value.','$_SESSION[prod]')";
if($conn -> query($q1) == TRUE){
echo "Data Entered successfully\n";
} else {
echo 'Error' . mysqli_error($conn);
}
}
} else {
$value = $_GET['checkbox'];
echo $value;
}
}
}
?>
And in the last file all the data are commited into the database.
Please tell me if anything i can do to improve my code.
Thank you.

Loading data from database with php and pure ajax in a textbox

i have one dropdown list which has data for "subjects" loaded from database. when i clicked on one subject what it should do is load related "subject_id" value inside textbox which is just below dropdown list option. i dont know how to bring value from getbook.php and show in book_ID input text.
show_bookid(str) {
var xmlhttp;
if (str.length == 0) {
document.getElementById("bookid").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
strong text
xmlhttp = new ActiveXOjbject("Microsoft.XMLHttpRequest");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("bookid").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getbook.php?q=" + str, true);
xmlhttp.send();
}
getbook.php
<?php
<?php
$b = $_GET['q'];
include('includes/security.php');
include('includes/dbconnect.php');
$database = new MySQLDatabase();
$sql = "select * from tbl_bkcat where book_id='" . $b . "'";
$result = mysql_query($sql);
?>
?>
below is the File where i need to bring value
<form name="bookadd" action="" class="jNice" method="post">
<p>
<label>Subject</label>
<select name="subject" onChange="show_bookid(this.value);">
<?php while($sel_rows=mysql_fetch_array($subresult)) { ?>
<option value="<?php echo $sel_rows['book_id'];?>">
<?php echo $sel_rows[ 'subject']?>
</option>
<?php } ?>
</select>
</p>
<p>
<label>Book_Id</label>
<input type="text" id="bookid" class="text-small" />//where i need to load subject id</p>
The mistake was done at ajax part document.getElementById("bookid").innerHTML and must be replaced with document.getElementById().value since I had to put data to Html Element that cotain value i.e Textbox(as textbox contain value attribute).
InnerHTML is used to manipulate the html elements that does not contain value,
** div,h1, ** etc. for details see below link.
http://www.verious.com/qa/what-39-s-the-difference-between-document-get-element-by-id-quot-test-quot-value-and-document-get-element-by-id-quot-tes/
ajax code
function show_bookid(str)
{
var xmlhttp;
if(str.length==0)
{
document.getElementById("bookid").value="";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp= new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXOjbject("Microsoft.XMLHttpRequest");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("bookid").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getbook.php?q="+str,true);
xmlhttp.send();
}
getbook.php
<?php
$b=$_GET['q'];
include('includes/security.php');
include('includes/dbconnect.php');
$database=new MySQLDatabase();
$sql="select * from tbl_bkcat where book_id='".$b."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
echo $row['Book_id'];
?>
addbook.php
<form name="bookadd" action="" class="jNice" method="post">
<fieldset>
<p><label>Subject</label>
<select name="subject" onChange="show_bookid(this.value);">
<?php
while($sel_rows=mysql_fetch_array($subresult))
{
?>
<option value="<?php echo $sel_rows['book_id'];?>">
<?php echo $sel_rows['subject']?>
</option>
<?php
}
?>
</select>
</p>
<p>
<label >Book ID</label>
<input type="text" id="bookid" name="book"/>
</p>
Your subject_id is not displaying because you have not printed your book_id after fetching results from database in getbook.php
After this $result=mysql_query($sql);
Write echo $result['your_book_id_field_name'];

how do i fill text box field with ajax

I have a combobox and i want to fill the State and Zip_code Field..its working but it fills each field State "NY11715" and Zip_code "NY11715"...i'm looking to fill State "NY" and Zip_code 11715...please help me resolve this
<select name="LookupCity" id="LookupCity" onchange="showZip(this.value)">
<option value="" <?php if (!(strcmp("", $_GET['City']))) {echo "selected=\"selected\"";} ?>>Select from menu</option>
<?php do { ?>
<option value="<?php echo $row_fmCity['City']?>"<?php if (!(strcmp($row_fmCity['City'], $_GET['City']))) {echo "selected=\"selected\"";} ?>><?php echo $row_fmCity['City']?></option>
<?php
} while ($row_fmCity = mysql_fetch_assoc($fmCity));
$rows = mysql_num_rows($fmCity);
if($rows > 0) {
mysql_data_seek($fmCity, 0);
$row_fmCity = mysql_fetch_assoc($fmCity); } ?> </select>
select</td>
</tr><tr valign="baseline">
<td nowrap="nowrap" align="right">State:</td>
<td><input type="text" name="State" id="State" placeholder="NY" value="<?php echo $_GET['State']; ?>" size="5"/>
<input type="text" name="Zip_Code" id="Zip_Code"placeholder="zip code" value="<?php echo $_GET['Zip']; ?>" size="10" /></td>
Ajax code
function showZip(str)
{
if (str=="")
{
document.getElementById("State").innerHTML="";
document.getElementById("Zip_Code").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Getzip.php?q="+str,true);
xmlhttp.send();
}
PHP Code
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Leadbook", $con);
$sql="SELECT * FROM Zip WHERE City = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$State = $row['State'];
$Zip_Code = $row['Zip Code'];
}
echo $State;
echo $Zip_Code;
mysql_close($con);
?>
1. change your php code, so that both city and zip code are comma seperated.
change this code:
echo $State;
echo $Zip_Code;
to this:
echo $State;
echo ",";
echo $Zip_Code;
2. than update your javascript, so that the return text is splitted into 2 parts and gets to its respected fields.
change this code:
document.getElementById("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
to this:
var string = xmlhttp.responseText;
var array = string.split(',');
document.getElementById("State").value=array[0];
document.getElementById("Zip_Code").value=array[1];
this should do what you requested.

Javascript function not being called from onchange (not always)

At the moment, I'm in the process of creating a website, where I have some products which have a quantity. This quantity depends on a size and color.
So I came up with the following procedure to check and give feedback about how many there are still left.
<div class="product_stock" id="stock_form<?php echo $i; ?>"><?php
$size = $product_sizes[0];
$color = $product_colors[0];
$sql = "SELECT * FROM products WHERE product_id = '$product_id' AND size = '$size' AND color = '$color'";
$result = mysql_query($sql) or die(mysql_error());
echo $sql;
if(mysql_num_rows($result) > 0) {
$product_stock = mysql_fetch_array($result);
if($product_stock['stock'] > 0) {
echo "Nog ".$product_stock['stock']." verkrijgbaar";
} else {
echo "Combinatie is niet meer verkrijgbaar";
}
}?>
</div>
<div class="product_text">
<?php echo $product['text']; ?>
</div>
<div class="product_num">
art: #<?php echo $product['product_id']; ?>
</div>
<div class="product_bar_bot">
<form name="form<?php echo $i; ?>" action="shopping_cart.php?">
<input type="hidden" name="id" value="<?php echo $product['pid']; ?>"/>
<select name="size" class="product_select" onChange="get_stock('form<?php echo $i; ?>');">
<?php foreach($product_sizes as $p_size) { ?>
<option>
<?php echo $p_size; ?>
</option>
<?php } ?>
</select>
<select name="color" class="product_select" onChange="get_stock('form<?php echo $i; ?>');">
<?php foreach($product_colors as $p_color) { ?>
<option value="<?php echo $p_color; ?>">
<?php echo $color_array[$p_color]; ?>
</option>
<?php } ?>
</select>
<input type="hidden" name="url" value="sale">
<input type="hidden" name="action" value="add">
<input type="text" name="amount" value="1" size="1" style="vertical-align: top; margin-top: 9px;"></input>
<img src="images/icons/cart_shop.png" align="top"/>
<input type="submit" class="button" value="Voeg toe" style="vertical-align: top; margin-top: 7px;">
The function that is required to be called:
function get_stock(formid) {
var form = document.forms[formid];
var size = form.size.value;
var color = form.color.value;
var pid = form.id.value;
var stock = 'stock_'+formid;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(stock).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_stock.php?id="+pid+"&size="+size+"&color="+color,true);
xmlhttp.send();
}
The problem I'm having is that it does work for some of the forms, but for some forms the get_stock.php page isn't even being called.
If more information is needed don't hesitate to ask.
I made a small error that I already fixed, thanks to #Bergi's comment. I was creating the forms by adding +1 at $i each time, but I reseted $i at the wrong place, which resulted in more then one of $i = 1 for example.

Using PHP to query db, fetch results via AJAX as variable, query db again using values of initial variable

It's all in the question really :)
It's clearer when I put it in bullet points what I want to do, so here it goes:
I have two forms on a page, a search form, and an 'edit profile' form. Both are in working order, individually.
The edit profile form paginates through the rows of my MySQL tbl, allowing my to edit the values for each column. Currently set up to include all rows (i.e. all stored profiles).
the search form takes any of 17 different search variables and searches that same table to find a profile, or a group of profiles.
I want to be able to enter a search term (e.g. Name: 'Bob'), query the tbl as I am doing, but use AJAX to return the unique ID's of the results as an an array stored within a variable. I then want to be able to asynchronously feed that variable to my edit profile form query (the search form would have a submit button...) so I can now page through all the rows in my table (e.g. where the Name includes 'Bob'), and only those rows.
Is the above possible with the languages in question? Can anyone help me piece them together?
I'm at an intermediate-ish stage with PHP and MySQL, but am an absolute novice with AJAX. I've only ever used it to display a text string in a defined area - as seen in demos everywhere :) Therefore, treating me like a five-year-old is greatly appreciated!
Here are my current search query, and the edit-profile form, if they help at all:
The Edit Profile form:
//pagination base
if (isset($_GET['page'])) { $page = $_GET['page']; }
else { $page = 1; }
$max_results = 1;
$from = (($page * $max_results) - $max_results);
$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM profiles"),0);
$total_pages = ceil($total_results / $max_results);
echo '<span id="pagination">' . 'Record ' . $page . ' of ' . $total_results . ' Records Returned. ';
if($total_results > $max_results)
{
if($page > 1)
{ $prev = ($page - 1);
echo "<input type='submit' value='<<' />";
}
if($page == 1)
{ echo "<input type='submit' value='<<' />"; }
if($page < $total_pages)
{ $next = ($page + 1);
echo "<input type='submit' value='>>' />";
}
if($page == $total_pages)
{ echo "<input type='submit' value='>>' />";
}
}
echo '</span></p>';
?>
// the query, currently selecting all but which I would have include a WHERE clause (WHERE ProfileID = $profileid...)
<?php
$sql = ("SELECT * FROM profiles
ORDER BY ProfileID
LIMIT $from, $max_results");
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
$profile = $row['ProfileID'];
?>
<form id="profile-form" action="profile-engine.php" method="post">
<input type="hidden" name="formid" value="edit-profile">
<input type="hidden" name="thisprofile" value="<?php echo $profile; ?>">
<table id="profile-detail" class="profile-form">
<tr>
<td>
<label for="profile-name">Name:</label>
<?php
$nameresult = mysql_query("SELECT ProfileName
FROM profiles
WHERE ProfileID = '$profile'");
$row = mysql_fetch_array($nameresult);
?>
<input type="text" class="text" name="profile-name" id="profile-name" value="<?php echo $row['ProfileName']; ?>" />
</td>
//goes on in this vein for another 16 inputs :)
The Search Query:
//connection established
$query = "SELECT * FROM profiles";
$postParameters = array("name","height","gender","class","death","appro","born","tobiano","modifier","adult","birth","sire","dam","breeder","owner","breed","location");
$whereClause = " WHERE 1 = 1";
foreach ($postParameters as $param) {
if (isset($_POST[$param]) && !empty($_POST[$param])) {
switch ($param) {
case "name":
$whereClause .= " AND ProfileName LIKE '%".$_POST[$param]."%' ";
break;
case "height":
$whereClause .= " AND ProfileHeight='".$_POST[$param]."' ";
break;
case "gender":
$whereClause .= " AND ProfileGenderID='".$_POST[$param]."' ";
break;
//more cases....
}
}
}
$query .= $whereClause;
$result = mysql_query("$query");
$values = array();
while ($row = mysql_fetch_array($result)) {
$values[] = $row['ProfileID'];
}
/*
//just me checking that it worked...
foreach( $values as $value => $id){
echo "$id <br />";
}
*/
mysql_close($con);
So, there you have it! Thanks in advance for any help!
what about:
search copies search term to local variable, service returns an array of results that you hold, and then pagination uses JS to drop in the values into the appropriate fields. If you change one and save, it submits the edits, including the original search term, which is used to re-query the service, and returns the updated array...repeat as necessary
here's some sample code (here there's just two search fields, I know you need more):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var query = new Object();
var resp;
var i;
function next(on){
i=on+1;
if(i==resp.results.length){i--;}
fillForm(i);
}
function prior(on){
i=on-1;
if(i<0){i++;}
fillForm(i);
}
function fillForm(i){
document.getElementById("paginate").innerHTML='<button onclick="prior('+i+')"><</button>'+(i+1)+' of '+resp.results.length+'<button onclick="next('+i+')">></button>';
document.getElementById("name").value=resp.results[i].name;
document.getElementById("height").value=resp.results[i].height;
document.getElementById("gender").value=resp.results[i].gender;
document.getElementById("class").value=resp.results[i].class;
document.getElementById("death").value=resp.results[i].death;
document.getElementById("appro").value=resp.results[i].appro;
document.getElementById("born").value=resp.results[i].born;
document.getElementById("tobiano").value=resp.results[i].tobiano;
document.getElementById("modifier").value=resp.results[i].modifier;
document.getElementById("adult").value=resp.results[i].adult;
document.getElementById("birth").value=resp.results[i].birth;
document.getElementById("sire").value=resp.results[i].sire;
document.getElementById("dam").value=resp.results[i].dam;
document.getElementById("breeder").value=resp.results[i].breeder;
document.getElementById("owner").value=resp.results[i].owner;
document.getElementById("breed").value=resp.results[i].breed;
document.getElementById("location").value=resp.results[i].location;
document.getElementById("id").value=resp.results[i].id;
document.getElementById("saveButton").innerHTML='<button onclick="save()">Save</button>';
}
function getData(){
query.name=document.getElementById('query_name').value;
query.gender=document.getElementById('query_gender').value;
var variables='';
variables+='name='+query.name;
variables+='&gender='+query.gender;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
resp = JSON.parse(xmlhttp.responseText);
fillForm(0);
}
}
xmlhttp.open("GET","searchNav.php?"+variables,true);
xmlhttp.send();
}
function save(){
var saving="";
saving+='?q='+query;
saving+='&name='+document.getElementById('name').value;
saving+='&height='+document.getElementById('height').value;
saving+='&gender='+document.getElementById('gender').value;
saving+='&class='+document.getElementById('class').value;
saving+='&death='+document.getElementById('death').value;
saving+='&appro='+document.getElementById('appro').value;
saving+='&born='+document.getElementById('born').value;
saving+='&tobiano='+document.getElementById('tobiano').value;
saving+='&modifier='+document.getElementById('modifier').value;
saving+='&adult='+document.getElementById('adult').value;
saving+='&birth='+document.getElementById('birth').value;
saving+='&sire='+document.getElementById('sire').value;
saving+='&dam='+document.getElementById('dam').value;
saving+='&owner='+document.getElementById('owner').value;
saving+='&breed='+document.getElementById('breed').value;
saving+='&breeder='+document.getElementById('breeder').value;
saving+='&location='+document.getElementById('location').value;
saving+='&id='+document.getElementById('id').value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
resp = JSON.parse(xmlhttp.responseText);
fillForm(0);
}
}
xmlhttp.open("GET","saveEdits.php"+saving,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="search">
<table>
<tr><td>Name:</td><td><input type="text" id="query_name" /></td></tr>
<tr><td>Gender:</td><td><input type="text" id="query_gender" /></td></tr></table>
<button onclick="getData()">Search</button>
</div>
<div id="results">
<div id="paginate"></div>
<input type="hidden" id="id" />
<table>
<tr><td>Name:</td><td><input type="text" id="name" /></td></tr>
<tr><td>Height:</td><td><input type="text" id="height" /></td></tr>
<tr><td>Gender:</td><td><input type="text" id="gender" /></td></tr>
<tr><td>Class:</td><td><input type="text" id="class" /></td></tr>
<tr><td>Death:</td><td><input type="text" id="death" /></td></tr>
<tr><td>Appro:</td><td><input type="text" id="appro" /></td></tr>
<tr><td>Born:</td><td><input type="text" id="born" /></td></tr>
<tr><td>Tobiano:</td><td><input type="text" id="tobiano" /></td></tr>
<tr><td>Modifier:</td><td><input type="text" id="modifier" /></td></tr>
<tr><td>Adult:</td><td><input type="text" id="adult" /></td></tr>
<tr><td>Birth:</td><td><input type="text" id="birth" /></td></tr>
<tr><td>Sire:</td><td><input type="text" id="sire" /></td></tr>
<tr><td>Dam:</td><td><input type="text" id="dam" /></td></tr>
<tr><td>Breeder:</td><td><input type="text" id="breeder" /></td></tr>
<tr><td>Owner:</td><td><input type="text" id="owner" /></td></tr>
<tr><td>Breed:</td><td><input type="text" id="breed" /></td></tr>
<tr><td>Location:</td><td><input type="text" id="location" /></td></tr>
</table>
<div id="saveButton"></div>
</div>
</body>
</html>
and the search:
<?php
//connection established
$query = "SELECT * FROM profiles";
$postParameters = array("name","height","gender","class","death","appro","born","tobiano","modifier","adult","birth","sire","dam","breeder","owner","breed","location");
$whereClause = " WHERE 1 = 1";
foreach ($postParameters as $param) {
if (isset($_POST[$param]) && !empty($_POST[$param])) {
$whereClause .= " AND ".$param."='".$_POST[$param]."'";
}
}
$query .= $whereClause;
$result = mysql_query("$query");
echo "{\"results\":";
if($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
echo "[";
echo "{\"name\":\"".$row["name"]."\",";
echo "\"height\":\"".$row["height"]."\",";
echo "\"gender\":\"".$row["gender"]."\",";
echo "\"class\":\"".$row["class"]."\",";
echo "\"death\":\"".$row["death"]."\",";
echo "\"appro\":\"".$row["appro"]."\",";
echo "\"born\":\"".$row["born"]."\"";
echo "\"tobiano\":\"".$row["tobiano"]."\"";
echo "\"modifier\":\"".$row["modifier"]."\"";
echo "\"adult\":\"".$row["adult"]."\"";
echo "\"birth\":\"".$row["birth"]."\"";
echo "\"sire\":\"".$row["sire"]."\"";
echo "\"dam\":\"".$row["dam"]."\"";
echo "\"breeder\":\"".$row["breeder"]."\"";
echo "\"owner\":\"".$row["owner"]."\"";
echo "\"breed\":\"".$row["breed"]."\"";
echo "\"location\":\"".$row["location"]."\"";
//echo "\"id\":\"".$row["id"]."\"";
echo "}";
}
else{
echo "\"no\"}";
exit;
}
while($row = mysql_fetch_array($data,MYSQL_ASSOC)){
echo ",{\"name\":\"".$row["name"]."\",";
echo "\"height\":\"".$row["height"]."\",";
echo "\"gender\":\"".$row["gender"]."\",";
echo "\"class\":\"".$row["class"]."\",";
echo "\"death\":\"".$row["death"]."\",";
echo "\"appro\":\"".$row["appro"]."\",";
echo "\"born\":\"".$row["born"]."\"";
echo "\"tobiano\":\"".$row["tobiano"]."\"";
echo "\"modifier\":\"".$row["modifier"]."\"";
echo "\"adult\":\"".$row["adult"]."\"";
echo "\"birth\":\"".$row["birth"]."\"";
echo "\"sire\":\"".$row["sire"]."\"";
echo "\"dam\":\"".$row["dam"]."\"";
echo "\"breeder\":\"".$row["breeder"]."\"";
echo "\"owner\":\"".$row["owner"]."\"";
echo "\"breed\":\"".$row["breed"]."\"";
echo "\"location\":\"".$row["location"]."\"";
//echo "\"id\":\"".$row["id"]."\"";
echo "}";
}
echo "]}";
?>

Categories