Issue With the Ajax's derived Selection box - php

<script type="text/javascript" src="jquery-1.js"></script>
<style type="text/css">
div {
height:25px;
}
label {
text-align:left;
width:100px;
display:inline-block;
vertical-align:top;
}
input {
margin-right:5px;
}
</style>
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
// $('select').toggle();
$('input').click(function(event) {
$(this).closest('div').children('select').toggle();
});
});
//]]>
</script>
<?php
#mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
$query = "select id,language,code from language WHERE first=1";
$results = mysql_query( $query);
$lang = array();
while ($rows = mysql_fetch_assoc(#$results)){
$lang[$rows['language']] = $rows['code'];
}
?>
<form action="" method="post" name="myForm" id="myForm" >
<?php
foreach($lang as $key=>$value){ ?>
<div>
<label for="lang_<?=$value;?>" >
<input name="language[<?=$value;?>]" id="lang_<?=$value;?>" value="1" type="checkbox">
<?=$key;?>
</label>
<select style="display: none;" name="level[<?=$value;?>]" id="f_level_<?=$value;?>">
<option selected="selected" value="">your level</option>
<option value="Low">Low</option>
<option value="Average">Average</option>
<option value="Fluent">Fluent</option>
<option value="Native">Native</option>
</select>
</div>
<?php } ?>
<input value="submit" name="submit" type="submit">
<!--**********************************************************-->
<br />
<br />
<br />
<script type="text/javascript">
function showCD(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("newone").innerHTML=xmlhttp.responseText;
$('#newone').append(xmlhttp.responseText);
// document.getElementById('newone').appendChild(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "123.php?q=" + str, true);
xmlhttp.send();
}
</script>
<?php
#mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
$query = "select id,language,code from language WHERE first=0";
$results = mysql_query( $query);
$lang = array();
while ($rows = mysql_fetch_assoc(#$results)){
$lang[$rows['language']] = $rows['code'];
}
?>
<select name="level[]" id="f_level" onchange="showCD(this.value)">
<option selected="selected" value="">language</option>
<?php
$results = mysql_query( $query);
while ($rows = mysql_fetch_assoc(#$results)){
?>
<option value="<?php echo $rows['id'];?>" ><?php echo $rows['language'];?></option>
<?php
}
?>
</select>
<div id="newone"></div>
</form>
---------------
<?php
mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
if($_REQUEST)
{
$id = $_REQUEST['q'];
$query = "select id,language,code from language where id = ".$id;
$results = mysql_query( $query);
$rows = mysql_fetch_assoc($results );
if($rows!='')
{?>
<div>
<label for="lang_<?=$rows['code'];?>" >
<input name="language[<?=$rows['code'];?>]" id="lang_<?=$rows['code'];?>" value="1" type="checkbox">
<?=$rows['language'];?>
</label>
<select style="display: none;" name="level[<?=$rows['code'];?>]" id="f_level_<?=$rows['code'];?>">
<option selected="selected" value="">your level</option>
<option value="Low">Low</option>
<option value="Average">Average</option>
<option value="Fluent">Fluent</option>
<option value="Native">Native</option>
</select>
</div>
<?php
}
return;
}
?>

Unfortunately I can't yet comment everywhere so apologies for adding an answer when a comment would have sufficed.
2 suggestions for you:
1) You are using jQuery but not making use of its excellent AJAX functions. Take a look at them.
2) You are suppressing PHP warnings and errors that may be helpful to you debugging this yourself. Remove the # from the front of several of these function calls and run it again. Maybe you will see the problem yourself.
The only other thing that jumped out at me while scanning this code (since I have no idea what your problem is) is that the derived responce does not include the 'onchange' event that all of your other selects do. Is it a simple oversight?

Related

getting a text value populated by a select option

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

Function not renaming field pulled from another page

I have a form which is cloned when needed, inside this form I have a div, this div is replaced by a div pulled from another page which has new select options based on a select option from a above field.
Each 'cloned' forms fields are given a new name with a function, but this function seems to have trouble seeing the field that is pulled in as part of the form and isn't generating a new name for it.
Could Someone kind enough show me the way please?
function;
$(document).ready(function() {
var newNum = 2;
cloneMe = function(el) {
var newElem = el.clone().attr('id', 'container' + newNum);
newElem.html(newElem.html().replace(/form\[1\]/g, 'form['+newNum+']'));
newElem.html(newElem.html().replace(/id="(.*?)"/g, 'id="1'+newNum+'"'));
$('#cloneb').before(newElem);
$('#delete_name'+ newNum).html('<p id="rem_field"><span>Delete Line</span></p>');
newNum++;
};
$('p#rem_field').live('click', function() {
$(this).parents('div').remove();
return false;
});
});
form;
<form action='' method='post' enctype='multipart/form-data' name='form' id='form'>
<div id="container1">
<div class="instance" id="instance">
<label>Style:</label>
<select name='form[1][style]' id='style' class='style' onchange="showDim(this)">
<option value='0' class='red'>Select a style...</option>
<?php
include ('connect.php');
$getsty = $db->prepare("SELECT Style_ID, Style_Type FROM style ORDER BY Style_Type ASC LIMIT 1, 18446744073709551615;");
$getsty->execute();
while($row = $getsty->fetch(PDO::FETCH_ASSOC)) {
$Style_ID = $row['Style_ID'];
$Style_Type = $row['Style_Type'];
echo " <option value='$Style_ID'>$Style_Type</option>";
}
?>
</select>
<br />
<div class='dimdiv'>
<label>Dimensions:</label>
<select name='form[1][Dim]' id='Dim'>
<option value='0' class='red'>Select the dimensions...</option>
</select>
</div>
<br />
<label>Colour:</label>
<select name='form[1][Colour]' id='Colour'>
<option value='0' class='red'>Select a colour...</option>
<option value='Colour1'>Colour #1</option>
<option value='Colour2'>Colour #2</option>
<option value='Colour3'>Colour #3</option>
<option value='Colour4'>Colour #4</option>
</select>
<br />
<label>Quantity:</label>
<input type='text' name='form[1][Quantity]' id='Quantity'>
<br />
</div>
<div id="delete_name" style="margin:15px 0px 0px 0px; width:120px; height:30px;"></div>
</div>
<input type="button" id="cloneb" value="Clone" onclick="cloneMe($('#container1'));" />
<input type='submit' name='submit' value='Submit' class='buttons'>
</form>
Field pulled from get_dim.php;
<label>Dimensions:</label>
<select name='form[1][Dim]' id='Dim'>
<option value='0' class="red">Select the dimensions...</option>
<?php
$id = intval($_GET['id']);
include ('connect.php');
$getcus = $db->prepare("SELECT Dim_ID, Dim FROM dimentions WHERE Style_ID=? ORDER BY Dim ASC ");
$getcus->execute(array($id));
while($row = $getcus->fetch(PDO::FETCH_ASSOC)) {
$Dim_ID = $row['Dim_ID'];
$Dim = $row['Dim'];
echo " <option value='$Dim_ID'>$Dim</option>";
}
?>
</select>
Function to replace the dimdiv with get_dim.php;
function showDim(elem)
{
var elems = document.getElementsByClassName('style'),
groupIndex = -1,
targetDimDiv,
i;
for( i = 0; i < elems.length; ++i ) {
if( elems[i] == elem ) {
groupIndex = i;
break;
}
}
if( groupIndex == -1 )
{
return;
}
targetDimDiv = document.getElementsByClassName('dimdiv')[groupIndex];
if (elem.value == "")
{
targetDimDiv.innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function( ) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
targetDimDiv.innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","get_dim.php?id="+elem.value,true);
xmlhttp.send();
}
Your problem is, that form[1][Dim] is hard coded into get_dim.php. When you clone a form, you change the name of every element, but this AJAX request would still return a form element with name form[1][Dim] there too.
You can fix this, by reading out the current form id and passing it to get_dim.php and making the name generation there dynamic.
The parts you have to change (roughly):
replace function:
form_id = groupIndex + 1; // if I get groupIndex right
xmlhttp.open("GET","get_dim.php?id="+elem.value+"&form_id="+form_id,true);
get_dim.php:
<select name='form[<?php echo intval($_GET['form_id']); ?>][Dim]' id='Dim'>

form does not posting the data of filtered field?

i am fetching categories and their sub-categories from the database.
and filtering the sub-categories after selecting the category bu using dropdown.
after selecting when i submit the form, the value of the sub-category is 0, form does not posting the selected value.
<?php
if(isset($_POST) && $_POST['submit'] == "Add")
{
extract($_POST);
$scat_id = $regions['scat_id'];
echo $sqlpa = "INSERT INTO products(mcat_id, scat_id)VALUES('$mcat_id', '$scat_id')";
$resultpa = mysql_query($sqlpa);
}
?>
<script type="text/javascript">
function getregions(mcat_id) {
if (mcat_id=="") {
document.getElementById("region").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("region").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getregions.php?mcat_id="+mcat_id,true);
xmlhttp.send();
}
</script>
<form action="" method="post" name="p_add" id="p_add">
<table>
<tr>
<td>Select Category</td>
<td><select name="mcat_id" id="mcat_id" onchange="getregions(this.value);">
<option value="">Select</option>
<?php
if(!empty($resultm)) {
foreach($resultm as $rm) {
?>
<option value="<?php echo $rm['mcat_id']; ?>"><?php echo $rm['mcat_name'];?> (<?php echo $rm['mcat_id']; ?>)</option>
<?php
}
}
?>
</select>
</td>
</tr>
<tr>
<td>Select Sub-Category</td>
<td>
<div id="region">
<select name="scat_id" id="scat_id">
<option value="">Please Select</option>
</select>
</div>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add" /></td>
</tr>
</table>
</form>
-->this page is getregions.php where filtering is done:
<?php
include "../conn.php";
$mcat_id=$_GET['mcat_id'];
$sql = "SELECT * FROM sub_category WHERE mcat_id = '".$mcat_id."'";
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
$rec[] = $row ;
}
?>
<select name="scat_id" id="scat_id">
<option value="">Please Select</option>
<?php
foreach($rec as $regions) {
?>
<option value="<?php echo $regions['scat_id'];?>"><?php echo $regions['scat_name'];?></option>
<?php
}
?>
</select>
just before the insert query, i need to write
$scat_id = $_post['scat_id'];
this will get the posted value.

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.

dropdown with php and ajax

For some time I am battling to solve this problem but I am not coming to any conclusion so thought to seek some help here.
The problem is that I am getting a blank dropdown instead I should get list of cities populated from the database. Database connection is fine but I am not getting anything in my dropdown.
This is what I am doing:
<?php
require 'includes/connect.php'; - database connection
$country=$_REQUEST['country']; - get from form (index.php)
$q = "SELECT city FROM city where countryid=".$country;
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
if ($result) {
?>
<select name="city">
<option>Select City</option>
$id = 0;
<?php while ($row = $result->fetch_object()) {
$src = $row->city;
$id = $id + 1;
?>
<option value= <?php $id ?> > <?php $src ?></option>
<?php } ?>
</select>
<?php } ?>
ajax script is this:
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{mlhttp=new XMLHttpRequest();}
catch(e) {
try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e){ try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
This is my form code:
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Country</td>
<td width="150"><select name="country" onChange="getCity('findcity.php?country='+this.value)">
<option value="">Select Country</option>
<option value="1">New Zealand</option>
<option value="2">Canada</option>
</select></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="citydiv"><select name="city">
<option>Select City</option>
</select></div></td>
</tr>
</table>
</form>
I think the problem is where you are outputting the <option> tags.
Try using this block of code between your <select> tags.
<option>Select City</option>
<?php
$id = 0;
while ($row = $result->fetch_object()) {
$src = $row->city;
$id = $id + 1;
?>
<option value="<?php echo htmlspecialchars($id,ENT_QUOTES) ?>"><?php echo htmlspecialchars($src) ?></option>
<?php } ?>
Edit: To clarify, you didn't have any echo statements before the $id and $src variables. I added htmlspecialchars() as a habit to produce properly escaped html.
A few things to try:
If you request findcity.php manually in your browser with a city you know exist in the database, will i return the correct HTML?
Try with FireBug or another javascript debugger, to set a breakpoint in the onreadystatechange function and see if the returned values are as expected. Set the breakpoint at the first line of the function.
<input name="acname" type="text" id="acname" value="" maxlength="9">
Account Name </p>
<select name="src">
<option value="number"> :::: Select ::::</option>
<option value="did">DID</option>
<option value="tfn">TFN</option>
</select>
<span id="errmsg"></span> DID/TFN </p>
<select name="did" onchange='OnChange(this.form1.did);' >
<option value=""> :::: Select ::::</option>
<? $qry1 = mysql_query("SELECT * FROM ".NUMBERS." where Flag='1'") or die(mysql_error()) ;
while($res1 = mysql_fetch_array($qry1)) { ?>
<option value="<?=$res1['Numbers'] ?>"><?=$res1["Numbers"]?></option>
<? } ?>
</select>
SOURCE

Categories