PHP HTML Form - AJAX Changes not submitted - php

I have a simple HTML Form that allows users to select a Type value. Based on the selected Type value they can then select from a list of Categories. The Categories are conditional based on the Type - when you select the Type a query is run against a database to select the matching Categories and display these as the select menu.
This is all working well as far as displaying the matching Categories, however when I submit the form the value for the selected Category is not part of the HTTP request and therefore nothing is being added to the database.
Here's the 2 fields in the HTML Form:
<div class="form-group">
<label for="type" class="control-label col-sm-3" >Type</label>
<div class="input-group col-xs-8">
<select class="form-control" name="type" id="type" onchange="getCategories(this.value)">
<option value=""></option>
<option value="Business">Business</option>
<option value="Commercial">Commercial</option>
<option value="Commercial Land">Commercial Land</option>
<option value="Land">Land</option>
<option value="Rental">Rental</option>
<option value="Residential">Residential</option>
<option value="Rural">Rural</option>
</select>
</div>
</div>
<div class="form-group">
<label for="category" class="control-label col-sm-3" >Category</label>
<div class="input-group col-xs-8" class="" id="categoryList">
<select class="form-control" name="category" id="category">
<option value=""></option>
</select>
</div>
</div>
Here's the script that is called when the users makes a Type selection:
function getCategories(str) {
if (str == "") {
document.getElementById("categoryList").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("categoryList").innerHTML = xmlhttp.responseText;
}
var status = xmlhttp.status == 200 ? 'success' : 'error'
var group = document.getElementById("categoryList")
group.classList.add(status)
}
xmlhttp.open("POST", "getPropertyCategories.php?type=" + str, true);
xmlhttp.send();
}
This is working fine to show the conditional Category select menu based on the Type selection, but the Category selection isn't included as part of the form submission.
The getPropertyCategories.php returns the following for example:
<select class="form-control" name="category" id="category">
<option></option>
<option value='Accommodation/Tourism'>Accommodation/Tourism</option>
<option value='Automotive' selected='selected' >Automotive</option>
<option value='Beauty/Health'>Beauty/Health</option>
<option value='Education/Training'>Education/Training</option><option value='Food/Hospitality'>Food/Hospitality</option>
<option value='Franchise'>Franchise</option><option value='Home/Garden'>Home/Garden</option>
<option value='Import/Export/Whole'>Import/Export/Whole</option>
</select>

Change the id of the select menu to match the id specified in the javascript - or vice versa
<select class="form-control" name="category" id="categoryList">
<option value=""></option>
</select>

Related

How to display an alert message if the value is blank in the form

I have a form (bootstrap) in the script and need it if the user does not select the language and the value "" is blank to display the alert message and that he had to choose a language to proceed on the next step.
(as you can see the empty value in the form: value" " represent "Select Language")
I am using that form for google widget tool for translation, and when the visitor dont click anything and proceed to save file into the database , in the database I get value: "Select language" , I need that they pick one of the languages from the dropdown menu.
This is the form code:
<div class="form-group">
<label for="recipient-name" class="col-form-label">Language:</label>
<input type="text" class="form-control langinput" id="country" value="" readonly>
<select class="form-control langselect" aria-label="Language Translate Widget" id="country" style="display: none">
<option value="">Select Language</option>
<option value="English">English</option>
<option value="Afrikaans">Afrikaans</option>
<option value="Albanian">Albanian</option>
<option value="Amharic">Amharic</option>
<option value="Arabic">Arabic</option>
here is the button code for saving files into the database:
<button style="margin-top: -5%" background-color="#357ae8" type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModal" data-whatever="#getbootstrap" onclick="lang1()">Save to Database</button>
lang1 Function:
var langPath = $("select.goog-te-combo option:selected").text();
/*document.getElementById("country").options[document.getElementById("country").selectedIndex].text = langPath;
document.getElementById("country").options[document.getElementById("country").selectedIndex].value = langPath;*/
document.getElementById("country").value = langPath;
//$(".langinput").value = langPath;
//$('input[type="text"][class="langinput"]').prop("value", "langPath");
//$('.langinput').text(langPath);
$('.langinput').attr('value', langPath);
//$(".langinput").display = "inline";
}
/*function stoppedTyping(){
if($('#subtitle').val().length > 1 && $('#country').val().length >0 ) {
document.getElementById('submit_button').disabled = false;
} else {
document.getElementById('submit_button').disabled = true;
}
}
function stoppedSelect(){
if($('#subtitle').val().length > 1 && $('#country').val().length >0 ) {
document.getElementById('submit_button').disabled = false;
} else {
document.getElementById('submit_button').disabled = true;
}
}*/
With bootstrap just add required to the select:
<select class="form-control langselect" aria-label="Language Translate Widget" id="country" style="display: none" required>
<option value="">Select Language</option>
<option value="English">English</option>
<option value="Afrikaans">Afrikaans</option>
<option value="Albanian">Albanian</option>
<option value="Amharic">Amharic</option>
<option value="Arabic">Arabic</option>
</select>
Edit
Change the buttons onclick to onsubmit:
<button style="margin-top: -5%" background-color="#357ae8" type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModal" data-whatever="#getbootstrap" onsubmit="lang1()">Save to Database</button>
Just recommending to rewrite this: <option value="">Select Language</option>
to this: <option selected disabled>Select Language</option>
When user clicks on the next button check if the select's value length is 0 and return it.

Creating dynamic button with Jquery

Hey guys I'm trying to create a dynamic button from a drop down list. for example, in the HTML code below...
function dropdownbutton(){
var make = document.getElementById("makelist");
var answer = make.options[make.selectedIndex].value;
alert("answer")
}
<div class="make">
<label>Make</label>
<select name="make" id="makelist" onchange="getId(this.value);">
<option value="">Select Make</option>
<option value="">1</option>
</select>
</div>
<div id="model">
<label>Model</label>
<select name="model" id="modellist" onchange="getId2(this.value);">
<option value="">Select Model</option>
<option value="">1</option>
<option value="">2</option>
</select>
</div>
<div id="year">
<label>Year</label>
<select name="year" id="yearlist" onchange="getId3(this.value);">
<option value="">Select Year</option>
<option value="">1</option>
<option value="">2</option>
</select>
</div>
<button id="dropdownbutton" onclick="dropdownbutton()" class="vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-rounded vc_btn3-style-3d vc_btn3-color-success">Dropdown</button>
I'm open to trying it in different languages but I would prefer to do it in php, I simply don't know how to get the values from each dropdown.
I have taken help of Jquery here, inside the dropdownbutton() function i call all the select box element.
And using .each function extracted the value selected value of dropdowns.
i check those value if not empty then created a button inside element having Id #append_new_button
Please check the below code it might solve your issue
Thanks
function dropdownbutton() {
jQuery('#append_new_button').html('');
jQuery('select').each(function(){
var select_value = jQuery(this).val();
var select_label = jQuery("#"+jQuery(this).attr('id')+" option[value='"+select_value+"']"). text();
if(select_value != ''){
jQuery('#append_new_button').append('<input type="button" id="'+select_value+'" value="'+select_label+'"></button>')
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="make">
<label>Make</label>
<select name="make" id="makelist">
<option value="">Select Make</option>
<option value="make_1">Make 1</option>
<option value="make_2">Make 2</option>
</select>
</div>
<div id="model">
<label>Model</label>
<select name="model" id="modellist" >
<option value="">Select Model</option>
<option value="model_1">Model 1</option>
<option value="model_2">Model 2</option>
</select>
</div>
<div id="year">
<label>Year</label>
<select name="year" id="yearlist" >
<option value="">Select Year</option>
<option value="year_1">year 1</option>
<option value="year_2">year 2</option>
</select>
</div>
<button id="dropdownbutton" onclick="dropdownbutton()" class="vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-rounded vc_btn3-style-3d vc_btn3-color-success">Dropdown</button>
<div id="append_new_button">
</div>
I updated that code to find the values for each drop down
function dropdownbutton(val){
var make = document.getElementById("makelist");
var answer = make.options[make.selectedIndex].value;
var model = document.getElementById("modellist");
var answer2 = model.options[model.selectedIndex].value;
var year = document.getElementById("yearlist");
var answer3 = year.options[year.selectedIndex].value;
alert(answer2);
}
Now i need to figure out how to pass these variables to a link for example, mydomain.com/answer/answer2/answer3
i think that this code is more dynamic.
$("button").click(function() { // if button is clicked
var arr = $('select').map(function() { // run through all selects and get value
return this.value
}).get();
var url = "http://exp.com"; // base for the url
arr.forEach(function(item) {
url = url + '/' + item; // append all options to the base url
});
window.location.href(url); // redirect to base url + all options
});
Don't forget to add value to your options. <option value="1">1</option>
Please look at jsfiddle for a working example

Jquery Chosen Select plugin doesn't Work in PHP Ajax response

I have two chosen select box for fetching values from MYSQL DB
When No-1 Select box change then No-2 select box generate from AJAX response.
Chosen Plugin in No-1 work perfectly. But When No-2 select box generate from ajax then chosen plugin doesn't work in No-2 select box.
Main.PHP
<div class="control-group">
<label for="textfield" class="control-label">Category<span>*</span></label>
<div class="controls">
<select name="category" id="category" multiple="multiple" class="chosen-select input-medium" required onchange="showSubCat(this.value)">
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
</select>
<input type='hidden' value='' id='categoryId' name='categoryId'>
</div>
</div>
<div class="control-group">
<label for="textfield" class="control-label">Sub Category</label>
<div class="controls">
<select name="subCat_2" id="subCat_2" multiple="multiple" class="chosen-select input-large">
<option value="">--- Select Sub Category---</option>
</select>
</div>
</div>
JS CODE :
var xmlhttp;
function showSubCat(str){
if( $('#category :selected').length > 0){
//build an array of selected values
var selectednumbers = [];
$('#category :selected').each(function(i, selected) {
selectednumbers[i] = $(selected).val();
});
}
//alert(selectednumbers);
document.getElementsByName('categoryId')[0].value = selectednumbers;
if (str==""){
document.getElementById("subCat_2").innerHTML="";
return;
}
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("subCat_2").innerHTML=xmlhttp.responseText;
//alert(xmlhttp.responseText);
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","MYurl.php?catId="+selectednumbers,true);
xmlhttp.send();
}
AJAX.PHP
echo "<option value=''>--- Select Sub Category --- </option>";
$sql="SELECT field FROM tableName WHERE condition;
$result = mysql_query($sql) or die('MySql Error' . mysql_error());
while($row = mysql_fetch_array($result)){
echo "<option value='1'> ----- Sub Option 1</option>";
}
Let me know what i have done Wrong..??
Assuming you're calling chosen on the 2nd list, try using
$('#subCat_2').trigger('chosen:updated');
after you update its list.
If you look at plugin page it indicates that
`You can trigger several events on the original select field to invoke a behavior in Chosen.
chosen:updated This event should be triggered whenever Chosen’s underlying select element changes (such as a change in selected options).`
You need to rebuild the selectbox with new data in it.
if (xmlhttp.readyState==4 && xmlhttp.status==200){
// bind new data
document.getElementById("subCat_2").innerHTML=xmlhttp.responseText;
// refresh chosen.
$('#subCat_2').trigger("chosen:updated");
}

Dynamically generate a single new drop down menu in a html form

I have a html form defined . I have a button for the user to select his occupation . If his occupation happens to be a student then i need to generate another new button dynamically . If the user selects anything other than a student then i dont want any new button . I am unsure how to do . Do i use jquery ? I have no idea to use jquery . Can some one help ? Any pointers
Thanks.
<?php
?>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('#occupation').change(function()
{
if($(this).val() == 'Student')
{
$('#school').show();
} else {
$('#school').hide();
}
});
});
</script>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<form>
<select name="occupation" id="occupation">
<option value="">- Select Occupation -</option>
<option value="Worker">Worker</option>
<option value="Student">Student</option>
</select>
<select name="school" id="school" style="display: none;">
<option value="">Select School Type</option>
<option value="4 Year">4 Year</option>
<option value="2 Year">2 Year</option>
</select>
</form>
</body>
</html>
Personally I accomplish this by placing the additional form element in the HTML, simply hidden like so:
<select name="occupation" id="occupation">
<option value="">- Select Occupation -</option>
<option value="Worker">Worker</option>
<option value="Student">Student</option>
</select>
<select name="school" id="school" style="display: none;">
<option value="">Select School Type</option>
<option value="4 Year">4 Year</option>
<option value="2 Year">2 Year</option>
</select>
Then you can use JS, as I prefer jQuery, to show the div or hide the div when applicable:
$(document).ready(function()
{
$('#occupation').change(function()
{
if($(this).val() == 'Student')
{
$('#school').show();
} else {
$('#school').hide();
}
});
});
Using jQuery would simplify this:
Let's say you have the following:
<form>
<select name="occupation">
<option value="Non-Student">Non-Student</option>
<option value="Student">Student</option>
</select>
</form>
Then the following would be used to append the button if the user selected 'Student':
$(function(){
$('select[name="occupation"]').change(function(){
var val = $(this).val();
if(val=='Student'){
$('form').append('<button>New Button</button>');
}
});
});

Disable search form fields?

I have a form set up which links to a database to show specific products with the requirement chosen, for example:
Category >
Manufacturer >
Paper Size >
Each of these drop downs have different attributes. The client has requested, that once Software is selected from the Category drop down that the paper size and speed drop downs become disabled.
How would I do this?
My code is:
<select id="category1">
<option value="all">All</option>
<option value="printers">Printers</option>
<option value="software">Software</option>
</select>
<label class="minus_margin">Manufacturer: </label>
<select id="manufacturer1">
<option value="canon">Canon</option>
<option value="HP">HP</option>
<option value="epson">Epson</option>
</select>
<label class="minus_margin">Paper Size: </label>
<select id="paper_size1">
<option value="all">A4 & A3</option>
<option value="A4">A4 Only</option>
</select>
<label class="minus_margin">Speed: </label>
<select id="speed1">
<option value="all">All</option>
<option value="20">0-20</option>
<option value="34">21-34</option>
<option value="44">35-44</option>
<option value="54">45-54</option>
<option value="69">55-69</option>
<option value="89">70-89</option>
<option value="90">90+</option>
</select>`
For example, user selects software, paper size and speed drop-downs become disabled.
Thanks
You could use the onChange event with jQuery to detect when the content of the drop-down has changed and just disable the drop down.
Something like:
$('#dropDown').change(function() {
if ($(this).attr("disabled") == false) { $(this).attr("disabled","disabled"); }
}
To Enable it back you would use something like:
$('#dropDown').removeAttr("disabled");
EDIT:
$('#category1').change(function()
{
var selected = $(this).val();
if (selected == 'software')
{
$('#paper_size1').attr("disabled","disabled");
$('#speed1').attr("disabled","disabled");
} else {
if ($('#paper_size1').attr("disabled") == true) { $('#paper_size1').removeAttr("disabled"); }
if ($('#speed1').attr("disabled") == true) { $('#speed1').removeAttr("disabled"); }
}
});

Categories