I have a html form that posts the data to a php file for processing, on this form there is a dynamically produced combo box that is produced from a php file using javascript. The combo box displays and functions fine when the page is loaded but when the form is submitted the value from this box isn't posted.
the JavaScript function is
function showUser(str) {
if (str == "") {
document.getElementById("selSubCat").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("selSubCat").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getSubCats.php?Cat="+str,true);
xmlhttp.send();
}
}
The html is
<td >Category:</td>
<td >
<select name="Cats" onchange="showUser(this.value)" ><?
$qryCats="SELECT * FROM tblCategories";
$resCats=mysql_query($qryCats,$dbMain);
while($rowCats = mysql_fetch_array($resCats)){
echo "<option value='".$rowCats['Name']."'>".$rowCats['Name']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td >Sub Category:</td>
<td id="selSubCat">
</td>
</tr>
And the php file:
<?
include("dbconfig.php");
$cat=$_GET['Cat'];
$qryCats="SELECT * FROM tblSubCats WHERE Parent='" .$cat. "'";
$resCats=mysql_query($qryCats,$dbMain);
if ($numrow=mysql_num_rows($resCats)>0){
echo "<select name='subCats'>";
while($rowCats = mysql_fetch_array($resCats)){
echo "<option value='" .$rowCats['Name']. "'>" .$rowCats['Name']. "</option>";
}
echo "</select>";
}
else{
echo " There are no sub categories ";
}
?>
Any suggestions will be appreciated, I can't figure out why everything else apart from the subcategory is posted
Check out the name attribute. In HTML its Cats but in your code you are using $_GET['Cat'];
It should be
$cat=$_GET['Cats'];
Solved, I had a table on the html page which the form was inside. I swapped the tags around so that the table is inside the form and the dynamic fields post just fine. Not sure why having a form within a table stopped these from posting but at least it works now.
Related
I am using this example to run an ajax data query from an mysql db, that returns a table.
This is working fine when text is manually typed into this input form eg:
But the search form has an autocomplete jquery script that will help the user along. When a value is chosen from the dropdown autocomplete values, the onchange event isn't recognized, no table shows.
My question is, how would I put a button at the end of the search form, to change this to 'onclick' event, rather than 'onchange'? The hurdle I am facing is that the input for 'client_address' is part of a larger form, and clicking submit on any button causes the page to try submit the entire form.
create_wt.php:
// autocomplete
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
source: 'backend_search_addressWT.php'
});
});
</script>
// retrieve data in table
<script>
function showUser(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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<div class="form-group <?php echo (!empty($client_address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<div class = "input-group">
<input id="clientsearch" type="text" name="client_address" onchange="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
<!---<span class="input-group-btn">
<button class="btn btn-success" value="submit" id="ajaxbtn" type="submit">Get Client Info</button>
</span> -->
</div>
<br><div id="txtHint"><b>Person info will be listed here...</b></div>
<span class="help-block"><?php echo $client_address_err;?></span>
</div>
ajax_get_client_info.php:
<?php
require_once 'config.php';
$q = trim($_GET['q']);
$query = $mysqli->query("SELECT * FROM client WHERE client_address LIKE '%".$q."%'");
//$data = array();
//while ($row = $query->fetch_assoc()) {
// $data[] = ($row);
//}
//echo json_encode($data);
echo "<table>
<tr>
<th>client_id</th>
<th>Client Name</th>
<th>Phone Number</th>
</tr>";
while($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['client_id'] . "</td>";
echo "<td>" . $row['client_name'] . "</td>";
echo "<td>" . $row['client_phone'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT:
create_wt:
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
select: function showUser(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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
}
{
source: 'backend_search_addressWT.php'
});
});
</script>
According to jQuery UI Autocomplete documentation:
http://api.jqueryui.com/autocomplete/#event-select
the select event of the autocomplete input does not accept the user's input as an argument but has 2 other: event, ui.
So you are trying to access the value: ui.item.value that is the selected item's value.
So that must be your problem.
CBroe has the same answer in the comments.
....
function getHint(value) {
if ((value !== "") && (typeof value !== 'undefined')) {
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 ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q=" + value, true);
xmlhttp.send();
return true; // return true to accept the selection of the user
} else {
document.getElementById("txtHint").innerHTML = "";
$(this).autocomplete( "close" ); // Close the autocomplete popup manual because by returning false negates the selection but it does not close the popup.
return false; // return false to negate the selection of the user
}
}
$( "#clientsearch" ).autocomplete({
select: function showUser(event, ui) {
return getHint(ui.item.value);
},
change: function showUser(event, ui) {
return getHint(ui.item.value);
},
{
source: 'http://www.example.com'
}
});
....
Be sure to read the documentation so you know how to treat this case from the start.
Hope this helps.
Change onchange in input box to onkeyup, that should solve, onchange is mainly used for radio buttons and checkboxes.
<input id="clientsearch" type="text" name="client_address" onkeyup="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
Use a input type button:
<input type="button" name="" id="">
and use its click event. Input type will not submit the form.
I am decent with PHP but brand new to AJAX. I am currently using AJAX to pull data dynamically from CMS and display within a div on the same page. Currently I am doing this with a selection / option using a form. I am wondering if there is a way i can do this with an A Href and how that might look. I don't want it to refresh the page but work like an A Href would do pass variable values.
Here is what I have.
<script>
function showOrder(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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getorder.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form>
<select name="orders" onchange="showOrder(this.value)">
<option value="">Select an order:</option>
<? foreach($orders as $order){ ?>
<option value="<? order::num(); ?>"><? order::customer(); ?></option>
<? } ?>
</select>
</form>
I have found out a way to do it what I wanted, it ultimately led to scrapping the A HREF method and going with a button instead.
Here is how I had to structure the button
<button onclick="showOrder(this.value)" value="<? echo order::num(); ?>"><? echo order::customer(); ?></button>
I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(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","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment
When I am building 2 dropdowns filling them from the database, the second dropdown is created when a value is picked from the first dropdown. But then, when I select an option in the second, my ajax is being executed. But when I have only one value in the second dropdown, it won't work. Even if I call the javascript function manualy.
The 2nd dropdown:
<?
include ('../dbconnect.php');
$query = "CALL get_projects(".$userid.",".$q.")";
$result = mysql_query($query);
$countprojects = mysql_num_rows($result);
if ($countprojects != 0){
echo '<select class="form-control" onchange="showContent(this.value)">'."\n";
if ($countprojects > 1){
echo "<option value='none' selected>Select project</option>";
}
while($rowprojecten = mysql_fetch_assoc($result)){
echo '<option value='.$rowprojecten['projectID'].'>'.$rowprojecten['projectname'].'</option>';
$lastvalue = $rowprojecten['projectID']; // see below why i did this
}
echo '</select>';
?>
the javascript function I wrote/copied:
function showContent(str)
{
if (str=="")
{
document.getElementById("project").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("project").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","./includes/ajax/getcontent.php?q="+str,true);
xmlhttp.send();
}
The phpfile what is called from this javascript:
<?
$q = intval($_GET['q']);
include ('../dbconnect.php');
$query = "CALL get_project(".$userid.",".$q.")";
$return = '<div id="project">';
$return .= $query;
$return .= '</div>';
echo $return;
mysql_close($con);
?>
Why do I see the div 'project' change when I select one, but does'nt it change when it is created?
I tried to call the function manualy with adding this to the first php file. But it also doesn't work.
if ($countprojects == 1){
echo '<script type="text/javascript">
showContent('.$lastvalue.')
</script>';
}
sorry for my bad english, I hope you can help me solve this.
This is because there is only one option in your second drop down list. you cannot fire change event if there is only on or zero options in drop down list. what you can do is add this code where your first Ajax call get fired when selection changes. and place your second Ajax call in inside below code.
if ($('#selectproject').children().length == 1) {
// make sure you have imported latest jquery. if not add this inside HTMl head : <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
var selectedProject = $('#selectproject').children()[0].value;
showContent(selectedProject); // i hope this is the function you are calling when executing. if not please replace your function call here.
}
I have a function that gets the value of a select menu and this work great. But i am trying to add another value to the function. So I thought I would use the title attribute for option (please see code below). The problem is the username parameter in my JavaScript function is undefined.
Does anybody have any ideas of what im doing wrong?
FORM
<form action="">
<select id="acyear" name="acyear" onchange="showyearlogdays(this.value, this.title)">
<option value="" label="">- Year -</option>
<?php
$is_business_result = mysql_query('SELECT DISTINCT(academic_year)FROM holiday_entitlement_business_manual WHERE employee = \'' . $username . '\'');
while($acyear_filter = mysql_fetch_array($is_business_result)) {
echo '<option value="'.$acyear_filter['academic_year'].'" title="'.$username.'"';
$datestr = $acyear_filter['academic_year'];
$currentyear = substr($datestr, 0, 4);
if(intval(substr($datestr,4,2)) < 8){$ayear = ($currentyear - 1).'/'.$currentyear;}
else{$ayear = ($currentyear).'/'.($currentyear + 1);}
echo '>';
echo $ayear;
echo '</option>';
}
?>
</select>
</form>
Javascript
function showyearlogdays(str, username)
{
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","days_yearlog.php?username="+username+"&q="+str,true);
xmlhttp.send();
}
You need to get the title attribute of the selected option. Your code is pointing to the title attribute of the select tag. Make the change below:
showyearlogdays(this.value, this.options[this.selectedIndex].title)
You should also address the security concern mentioned in the comments. The way your query is setup would make for a really simple SQL Injection attack. If you don't want to rearchitect it the way the commenter suggested, I would at least escape $username so that SQL can't be injected.