I have a form that posts data on click of the submit button an AJAX function is called which should GET the PHP processing page. However the processing page does not seem to getting called or receiving the posted data..the code snippets are below:
//the form
<form name="quicktransfer" action="" method="post">
<td style="width: 214px;padding-left: 5px;padding-right: 5px; cell-spacing:10px ">
<dl id='accService'>
<dt id='accHeader1'>Quick transfer</dt>
<dt class='accLinks1'>From.. </dt>
<dt class='accLinks1'>
<!-- Creates a select drop down box with useres bank account numbers as the options -->
<?php
$acc_tbl='accounts';
$cust = $_SESSION['custno'];
$result = mysql_query("SELECT accountNo FROM $acc_tbl WHERE custNo = '$cust'");
echo '<select name="acc_from">';
echo "<option value=\" \"></option>";
while($array = mysql_fetch_assoc($result))
{
echo "<option value=\"{$array['accountNo']}\">{$array['accountNo']}</option>\n";
}
echo '</select>';
?>
<!-- end of the select drop down -->
</dt>
<dt class='accLinks1'>To... </dt> <dt class='accLinks1'>
<!-- Creates a select drop down box with useres bank account numbers as the options -->
<?php
$acc_tbl='accounts';
$cust = $_SESSION['custno'];
$result = mysql_query("SELECT accountNo FROM $acc_tbl WHERE custNo = '$cust'");
echo '<select name="acc_to">';
echo "<option value=\" \"></option>";
while($array = mysql_fetch_assoc($result))
{
echo "<option value=\"{$array['accountNo']}\">{$array['accountNo']}</option>\n";
}
echo '</select>';
?>
<!-- end of the select drop down -->
</dt>
<dt class='accLinks1'>Amount.. </dt>
<dt class='accLinks1'><input type="input" name="amount" id="amount" size="10"/></dt>
<dt class='accLinks1'><input type="submit" name="transfer" value="transfer" onclick="loadQuickTransfer()"><br/><br/></dt>
</dl>
</form>
//the AJAX script
function loadQuickTransfer()
{
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)
{
document.getElementById("QuickTransfer").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","quicktransfer.php",true);
xmlhttp.send();
}
// the form processing page getting called
if(isset($_POST['transfer']) && $_POST['amount'] == "")
{
echo '<b><i>Select account (From..To..)<br/><br/>Type amount to transfer.</i></b>';
}
else
{
$transFrom = $_POST['acc_from'];
$transTo = $_POST['acc_to'];
$amount = $_POST['amount'];
$acc_tbl = 'accounts';
$trans_tbl = 'transactions';
$cust = $_SESSION['custno'];
$transfer = mysql_query("UPDATE $acc_tbl SET accountBalance = accountBalance -'$amount' WHERE custNo = '$cust' AND accountNo = '$transFrom'");
if($transfer)
{
$transfer2 = mysql_query("UPDATE $acc_tbl SET accountBalance = accountBalance + '$amount' WHERE custNo = '$cust' AND accountNo = '$transTo'");
}
else
{
echo '<b>Error.. Could not transfer<br/> Please try again!</b>';
exit();
}
if($transfer2)
{
echo '<b>Transfer complete..</b> ';
exit();
}
}
I just had a quick look, but it seems you never send any post variables on the XMLHttpRequest.send() call.
Related
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
I am working on a project at the moment. In iI am using ajax to update and calculate scores, which works fine. However, I have a color scheme that changes according to the score. The color does change, but only after the page is refreshed. Is there anyway I can get the color to change with refreshing the page?
Here is the code that I am using to assign colors:
<?php $row_class = "";
while($row = mysql_fetch_assoc($dbResult1))
{
if($row['total_mai'] <= 2)
$row_class = "success";
else if($row['total_mai'] >= 5)
$row_class = "danger";
else if($row['total_mai'] >= 3 and $row['total_mai'] < 5)
$row_class = "warning";
// echo $row_class;
?>
In another page, here is an example of one question, it has three answers and depending on the answer a color is assigned based on the score
<tr>
<td class="form-group col-md-6">Is the duration of therapy acceptable?</td>
<td class="form-group col-md-6">
<p class="radio-inline">
<input type="radio" name="therapydur" id="j1" value="0" <?php echo $j1; ?> required onchange="ajaxFunction('therapydur','<?php echo $count; ?>','0','<?php echo $row['p_id']; ?>')">
A
</input></p>
<p class="radio-inline">
<input type="radio" name="therapydur" id="j2" value="0" <?php echo $j2; ?> required onchange="ajaxFunction('therapydur','<?php echo $count; ?>','0','<?php echo $row['p_id']; ?>')">
B
</input></p>
<p class="radio-inline">
<input type="radio" name="therapydur" id="j3" value="1" <?php echo $j3; ?> required onchange="ajaxFunction('therapydur','<?php echo $count; ?>','1','<?php echo $row['p_id']; ?>')">
C
</input></p>
</td>
</tr>
Here is the ajax from the same page:
<script language="javascript" type="text/javascript">
function ajaxFunction(title,id,val,p_id)
{
//alert("test");
//alert(id);
//alert(val);
//alert(title);
//alert(p_id);
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)
{
//alert(xmlhttp.responseText);
var resp = xmlhttp.responseText;
var split_v = resp.split("__");
//alert(split_v.length);
//alert(split_v[1]);
document.getElementById("ajaxDiv_"+id).innerHTML=split_v[0];
document.getElementById("ajaxTotal").innerHTML=split_v[1];
}
}
xmlhttp.open("GET","ajax_mai.php?pdr_id="+id+"&value="+val+"&title="+title+"&p_id="+p_id,true);
xmlhttp.send();
return true;
}
</script>
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.
Im getting a set of values from the database to show in a drop down list. Once the user selected an item from the drop down list the selected item should be assigned to a SESSION variable. I tried this but yet it is not working. Please smeone help me to sort it out.
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "><option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result)){
echo "<option value='$row[Form_ID]'>$row[Form_Name]</option>";
echo
}
?>
</select>
So I need to store these values receive from $row[Form_ID] and $row[Form_Name] in 2 session variables named $_SESSION['Form_ID'] and $_SESSION['Form_Name']; Could someone explain me how I can assign the selected item's values to these two session variables.
The selected option element must have selected attribute.
You should try something like this:
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; ">
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result))
{
echo "<option value='{$row['Form_ID']}'";
if($row['Form_ID'] == $_SESSION['Form_ID'])
echo " selected";
echo ">{$row['Form_Name']}</option>";
}
?>
</select>
UPDATE:
You can store it in $_SESSION after the form submit
<?php
session_start(); // dont forget it!
if(isset($_POST['submit']))
{
$_SESSION['Form_ID'] = $_POST['Form_ID'];
$_SESSION['Form_Name'] = $_POST['Form_Name'];
}
?>
Try This:
In your page add this and create one more page "showValues.php"(This is the page where you want to create and use your session variable).Code of showValues.php is also given below for example.
<html>
<head>
<script>
function showValue(vals)
{
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)
{
var val= xmlhttp.responseText;
document.getElementById("tbl").innerHTML+=val;
}
}
xmlhttp.open("GET","showValues.php?vals="+vals,true);
xmlhttp.send();
}
</script>
</head>
<body>
<table id="tbl">
<tr>
<td>
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "><option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result)){
echo "<option value='$row[Form_ID]'>$row[Form_Name]</option>";
echo
}
?>
</select>
</td>
</tr>
</table>
</body>
</html>
showValues.php
<?php
session_start();
$vals=$_REQUEST['vals'];
$_SESSION['SelectValue']=$vals;
echo $_SESSION['SelectValue'];
?>
try this
<form name="my_name" method="POST" action="">
<select name="FormNameSelecting" id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "> //don't forget put name at select
<option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_assoc($result)){ //prefer using assoc that array
echo "<option value='" . $row['Form_ID'] . ":::" . $row['Form_Name'] . "'>" . $row['Form_Name'] . "</option>";
}
?>
</select>
<input type="submit" name="go" value="go"/>
</form>
<?php
if(isset($_POST['go'])){
$store_sesi = explode(":::",$_POST['FormNameSelecting']);
$_SESSION['ID'] = $store[0];
$_SESSION['Name'] = $store[1];
}
?>
hope this code help you
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.