How to display hidden field in a form after ajax response - php

I have this form which has one select field for main-category, one select field for sub-category and a hidden field. This hidden field is only displayed when a specific value chosen from sub-category.
This sub-category options are the result of ajax response from main-category.
Here is the form:
<form>
<select id='main-cat' name='maincat' onchange="sortSubcat(this.value)"/>
<option value="">Please select one category</option>
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
</select>
<div id='subcat-more'>
<select id='subcat' name='subcat'>
<option value=''>Please select a subcategory</option>
</select>
</div>
<div id='morefield' style='display:none'>
<input type='text' name='option1'/>
</div>
</form>
I have a Jquery code which handle this form validation, and it tells whether the #morefield is displayed or not. Here is part of this code:
$("#subcat").change(function(){
if (subcat.val() == 'sub-cat-one'){
$("#morefield").css("display","block");
}else{
$("#morefield").hide();
}
});
Unfortunately, Ajax response only displays option on screen however, it did not change in html so when I viewed source code, I don't see any option for sub-cat. Thats why even I chose option sub-cat-one, I would show the div #morefield.
Is there anyway to solve this problem?
Best Regards,
More informaiton:
Here is my ajax call:
function sortSubcat(str)
{
if (str=="")
{
document.getElementById("subcat").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("subcat").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/member/sortsubcat.php?q="+str,true);
xmlhttp.send();
}
Here is the php file:
<?php
require_once("../configs/dbconnect.php");
if (!empty($_GET['q'])){
$q = basename($_GET['q']);
$sql="SELECT * FROM subcat WHERE maincat=:q";
$result = $conn->prepare($sql);
$result->bindParam(':q', $q);
$result->execute();
echo "<option value=''>Please select a sub cat</option>";
foreach($result as $row)
{
echo "<option value='$row[name]'>$row[name]</option>";
}
}
else{
echo "<option value=''>Please select a subcat</option>";
}
$conn=null;
?>

You have to use
if ($(this).val() == 'sub-cat-one'){
instead of
if (subcat.val() == 'sub-cat-one'){
to access the correct html element (#subcat) in your onchange eventhandler.
You also shouldn't use the id subcat for more than one element. Currently the div and the select are having id subcat.

You have two elements ( div and select ) with same id subcat. id attribute should be unique for all elements .

I think you should try below suggestions:
Use AJAX success callback instead of using onchange.
if ($(this).val() == 'sub-cat-one')

I think I see where your problem is coming from, on each iteration you echo the result. And only that result gets returned to your ajax script. Do this in your php file:
$returned_string = '[';
foreach($result as $row)
{
$returned_string .= '{"name" : "'. $row[name]. '", "value" : "'. $row[name]. '"},';
}
$returned_string = substr($returned_string, 0, -1); //remove trailing ','
$returned_string .= ']';
header("Content-type: application/json");
echo $returned_string;
exit;
Then in your successCallback function:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = JSON.parse(xmlhttp.responseText);
var selectElement = document.getElementById('subcat');
for(var i = 0; i < response.length; i++)
{
var idx = i+1;
selectElement.options[idx] = new Option(response[idx].value, response[idx].name, false, false);
}
}
}
}

Related

How to display a loading message until the content is fully loaded

I am using "http://www.w3schools.com/Php/php_ajax_database.asp" for displaying data from database on onchange of dropdown list. I have a huge amount of data in database. So it's taking time to load. Hence I would like to display a loading message somewhere in the page until the data display.
Code:
<script>
function showUser(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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
<form>
<select name="users" onChange="showUser(this.value)" style="margin-left: -680px;margin-top: -10px;">
<option value="1">Current Projects</option>
<option value="2">All Projects</option>
</select>
</form>
</div></div>
<div id="txtHint"> /*Content*/ </div>
getuser.php:
Database queries to display data.
In my opinion it is easier to juse a javascribt library/framework like JQuery for Ajax requests or plain everything javascript. If you want to do it the old school way, that this should be able to help you out:
if(obj.readyState == 0)
{
document.getElementById('copy').innerHTML = "Sending Request...";
}
if(obj.readyState == 1)
{
document.getElementById('copy').innerHTML = "Loading Response...";
}
if(obj.readyState == 2)
{
document.getElementById('copy').innerHTML = "Response Loaded...";
}
if(obj.readyState == 3)
{
document.getElementById('copy').innerHTML = "Response Ready...";
}
if(obj.readyState == 4)
{
if(obj.status == 200)
{
return true;
}
else if(obj.status == 404)
{
// Add a custom message or redirect the user to another page
document.getElementById('copy').innerHTML = "File not found";
}
else
{
document.getElementById('copy').innerHTML = "There was a problem retrieving the XML.";
}
}
It's pretty easy actually, just put the message / image you want in the div, like that :
<div id="txtHint"> Loading... </div>
And when the data is loaded and JS :
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
This will empty the div and replace with the Ajax content.
Actually, I think your code is already working.

Access values of multiple checked boxes

I want to access the values of dynamically created check boxes.
# $db = mysql_connect("abc", "abc", "");
mysql_select_db("abc");
$strSQL = "SELECT * FROM student";
$rs = mysql_query($strSQL);
$num_rows = mysql_num_rows($rs);
echo "<i style='color:#fff'> Number of Students = ".$num_rows."</i>";
$i=1;
while($r = mysql_fetch_array($rs)){
echo "<tr>";
echo "<td class='promotetabledata'>".$r[7]."</td>";
echo "<td class='promotetabledata'>".$r[6]."</td>";
echo "<td class='promotetabledata'><input type='checkbox' class='pr' value='".$r[7]."'/></td>"; /*dynamically created check boxes*/
echo "</tr>";
$i++;
}
The results are displayed in a promoteresults div using AJAX
<form id="promotionform" action="promotestudents.php" method="POST">
<div id="promoteresults">The results will show up here..!!
</div>
<div style=" position:relative; margin-top:10px; padding-left:44%;">
<button type="submit" class="button black">Promoted</a>
</div>
</form>
When the promoted button is clicked I want to get the selected records and update their value. To update the records, I need PHP. I can access the selected records in Javascript using
var selected = document.getElementsByClassName('pr').checked;
But how do I get the checked records in the HTML form and their values in PHP
The AJAX call with Javascript
function getpromotestudents()
{
//alert("hi");
var xmlhttp;
var select1 = document.getElementById('promotefacultyselect1');
var facutlyselect = select1.options[select1.selectedIndex].value;
var select2 = document.getElementById('promotedepartmentselect1');
var deptselect = select2.options[select2.selectedIndex].value;
var select3 = document.getElementById('promotecourseselect1');
var courseselect = select3.options[select3.selectedIndex].value;
var select4 = document.getElementById('promoteyearselect1');
var yearselect = select4.options[select4.selectedIndex].value;
var select5 = document.getElementById('promotesemselect1');
var semselect = select5.options[select5.selectedIndex].value;
var the_data = 'faculty='+facutlyselect+' &dept='+deptselect+' &course='+courseselect+' &year='+yearselect+' &sem='+semselect;
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("searchresults").innerHTML=xmlhttp.responseText;
}
}*/
xmlhttp.open("POST", "getpromotestudents.php", true); // set the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // adds a header to tell the PHP script to recognize the data as is sent via POST
xmlhttp.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById("promoteresults").innerHTML = xmlhttp.responseText;
}
}
}
<td class='promotetabledata'><input type='checkbox' name='pr[]' value='".$r[7]."'/></td>
This is the PHP code I finally wrote to access all the checkboxes, and perform the required operations on the selected ones.
<?php
$checkbox = $_POST['pr'];
foreach($checkbox as $value){
if(isset($checkbox)){
echo '<script>alert("'.$value.'")</script>';
}
}
?>
Give each of the checkbox name property like this
<input type='checkbox' class='pr' value='8' name='chk[]'/>
Than in the php you can get them as follows
<?php
$chkbox = $_POST['chk'];
foreach($chkbox as $a => $b){
echo $chkbox[$a];
}
?>
Set each check box's name property to pr[], as in:
echo "<input type='checkbox' class='pr' name='pr[]' value='".$r[7]."'/>";
Then, the first checkbox will be at $_POST['pr'][0], the second at $_POST['pr'][1] and so on.

Jquery get value of element loaded with AJAX

I have a page with 2 select boxes, one of which is loaded by an AJAX call. I then want to validate the elements with jquery before I enable the submit button. The jquery works fine when I change the static select (strDirectorate) but not when I change the one loaded by AJAX (new_cc).
Is it because jquery is getting the value of new_cc as it was when the page was loaded?
<div class="selectfield">
<select id="strDirectorate" name="strDirectorate" class="mainform_select" onChange="getNewCostCentre(this.value)">
<option value="" selected="selected"></option>
<?php do { ?>
<option value="<?php echo $row_rsLocality['strLocalityShort']?>" <?php if($row_rsLocality['strLocalityShort'] == $strDirectorate){ echo $selected; } ?>><?php echo $row_rsLocality['strLocalityLong']?></option>
<?php
} while ($row_rsLocality = mysql_fetch_assoc($rsLocality));
$rows = mysql_num_rows($rsLocality);
if($rows > 0) {
mysql_data_seek($rsLocality, 0);
$row_rsLocality = mysql_fetch_assoc($rsLocality);
}
?>
</select>
</div>
<div id="txtNewCostCentre" class="selectfield">
<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">
<option value="" selected="selected"></option>
</select>
</div>
<div class="actions">
<input type="submit" id="submit_button" name="submit_button" class="styled_button" value="Submit" />
</div>
The function getNewCostCentre is
function getNewCostCentre(str)
{
if (str=="")
{
document.getElementById("txtNewCostCentre").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("txtNewCostCentre").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getNewCostCentre.php?q="+str,true);
xmlhttp.send();
}
The code for getNewCostCentre.php is
$sql="SELECT * FROM `tblcostcentreorganisation` WHERE `strOrganisation` LIKE '363 ".addslashes($dir)."%'";
$result = mysql_query($sql);
if(isset($_GET["q"])){
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)" style="background-color:#F8E0E0">';
$display_string .= '<option value="" selected="selected" disabled="disabled"></option>';
}else{
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">';
}
while($row = mysql_fetch_array($result))
{
$cc = substr($row['strCostCentre'], 3, strlen($row['strCostCentre'])-3) . " " . substr($row['strOrganisation'], 3, strlen($row['strOrganisation'])-3);
$org_name = $row['strOrganisation'];
if ($org == $org_name){
$display_string .= '<option value="'.$org_name.'" selected="selected">'.$cc.'</option>';
}else{
$display_string .= '<option value="'.$org_name.'">'.$cc.'</option>';
}
}
$display_string .= '</select>';
echo $display_string;
And the jquery validation is:
$(document).ready(function() {
$('.selectfield select').change(function() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
});
});
The onload code is as follows. I assume it's because I'm using .load within (after) .onload?
$(document).ready(function(){
window.onload = function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded);
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
});
You are binding your change handler for $('.selectfield select') when the page loads. This attaches the handler to all elements that match that selector.
If you then change this element, it won't have the handler attached.
Instead, you should use the live handler, to match all elements that exist now or are ever created in the future.
$('.selectfield select').live("change", function() {
...
});
UPDATE:
For you onload issue, it would be far easier not to repeat your code. If you need to fire off the validation after loading the content dynamically, then trigger the change event once the load has finished - like the following example:
$(document).ready(function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded, function() {
$('.selectfield select').trigger("change");
});
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
});
An ajax update of the input shouldn't trigger the javascript change event so the handler you've specified in change won't get called.
From the javascript specification (http://www.w3.org/TR/html401/interact/scripts.html) :
onchange = script [CT] The onchange event occurs when a control loses
the input focus and its value has been modified since gaining focus.
This attribute applies to the following elements: INPUT, SELECT, and
TEXTAREA.
I'd suggest performing the validation logic in the same part of your javascript where you're handling the response from the ajax request. Right after the line
document.getElementById("txtNewCostCentre").innerHTML=xmlhttp.responseText;
add the call
validate();
Where validate is earlier defined as :
function validate() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
So that your jquery validation becomes:
$(document).ready(function() {
$('.selectfield select').change(validate());

Using Ajax with multiple select

I have a multiple select form that I am now trying to use with AJAX. The drop down is supposed to act as a filter for images.
Index.php
<script>
function filterResults(str)
{
if (str=="")
{
document.getElementById("divResults").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("divResults").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","filter_ajax.php?filter="+str,true);
xmlhttp.send();
}
</script>
<form action="" class="css_form" id="picture_filter" name="picture_filter">
<select onchange="filterResults(this.value)" multiple="multiple" name="filter[]" id="filter">
<option value="filter_name_1">Filter name 1</option>
<option value="filter_name_2">Filter name 2</option>
<option value="filter_name_3">Filter name 3</option>
<option value="filter_name_4">Filter name 4</option>
</select>
<div id="divResults"></div>
and filter_ajax.php
<?php
include ("connect.php");
$filter = $_GET["filter"];
$filterIn = implode("','",$filter);
$result = mysql_query("SELECT * FROM edt_images
WHERE category1 IN ('$filterIn')
OR category2 IN ('$filterIn')
OR category3 IN ('$filterIn')
OR category4 IN ('$filterIn')
OR category5 IN ('$filterIn')
OR category6 IN ('$filterIn')")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "<img src='files/small/thumb0_".$row['item_name'].".".$row['file_extension']."' border='0'/>";
}
?>
In my database each image has six entries which correspond to the categories, and are filled with subcategories. Thus whats supposed to happen is that when an item is selected from the "filter drop-down" it should query each six columns for that information. However I am receiving the following error and output:
implode(): Invalid arguments passed in ... Line 6.
For testing I have five entries. 3 which have all information filled in for the six categories entries, and two which were left blank.
The two that are left blank are always returned with the error above.
Anyone have any ideas as to why this is happening?
Thanks in advance
Modify <select>:
<select onchange="filterResults(this)" multiple="multiple" name="filter[]" id="filter">
and try this (note: you don't need to implode array with "," on server-side - that is already done with JS in the example):
function filterResults(sel)
{
var selectedOptions = [];
for (var i = 0; i < sel.options.length; i++) {
if (sel.options[i].selected) {
selectedOptions.push("'" + sel.options[i].value + "'");
}
}
if (selectedOptions.length == 0) {
document.getElementById("divResults").innerHTML="";
return;
}
str = selectedOptions.join(",");
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("divResults").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?filter="+str,true);
xmlhttp.send();
}
UPD:
Modify your SQL also:
$result = mysql_query("SELECT * FROM edt_images
WHERE category1 IN ($filterIn)
OR category2 IN ($filterIn)
OR category3 IN ($filterIn)
OR category4 IN ($filterIn)
OR category5 IN ($filterIn)
OR category6 IN ($filterIn)");
What you're sending to your PHP script, is not an array. So you cannot use implode() on it and implode() is returning an error. Run this:
var_dump($filter);
Then you can decide how to modify your code based on the result.

how to write php MySql query

I would like to be able to make a selection from a select-box and view the selected table.
My skill level with php/MySQL at this point is:
$query = "SELECT * FROM electrical ORDER BY item_id LIMIT $offset, $RPP";
With this query the div is populated on page load.
I have a select box that has 6 choices:
<form>
<select name="dbtables" onchange="showTable(this.value)" id="selectBox">
<option value="">Select a materials table:</option>
<option value="" id="hr"></option>
<option value="equipment">Worker Equipment</option>
<option value="tool">General Tools</option>
<option value="electrical">Electrical Materials</option>
<option value="mechanical">Mechanical Materials</option>
<option value="plumbing">Plumbing Materials</option>
<option value="hvac">HVAC Materials</option>
</select>
</form>
Each choice is a table in a single MySQL database.
Script for showTable is working, after making selection alert shows choice picked.
function showTable(str) {
if (str == "") {
document.getElementById("materials").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("materials").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index.php?q=" + str, true);
xmlhttp.send();
alert(str);
}
Any pointers or help is appreciated appreciated.
I think what you're looking for is the SQL-query to execute on your database. What you should do is to insert the q-variable from the query string into the SQL-query like this
$query = "SELECT * FROM " . $_REQUEST['q'] . " ORDER BY item_id LIMIT $offset, $RPP";
Ofcourse you should check or escape the variables to prevent SQL injections, using something like mysql_real_escape_string, but that's not really the scope of this question.
in your index.php pick the $str value using $_GET method and construct the query. then run that query and echo the data. after that, you can call this function in the script file after alert().
function useHttpResponse() {
if (http.readyState == 4) {
if(http.status == 200) {
var txt = http.responseText;
var response_msg="<h4><span class='darkblue'>" + txt + "</span></h4>"
document.getElementById('showtime').innerHTML = response_msg;
}
} else { //you may skip this else portion
document.getElementById('showtime').innerHTML = '<img src="images/loading.gif" /><span class="darkblue">retrieving data...</span>';
}
}
here your fetched data will show on a div with id "showtime". during the fetching the time a loading gif will be visible in the "showtime" div. or you may skip that else portion.
hope that function will help you.

Categories