I have two dropdown lists. Both are to be filled by PHP via a mysql query. My problem is I want the form to be responsive if these list selections change. For instance, I need to populate the second list via another query based upon the selection of the first list.
Problem is: I need "on_change" to POST the form data AND to trigger PHP instead of Javascript.
Is there a way to collect that selection in Javascript and then send it to PHP and then refill the form? Hope I'm making myself clear.
Thanks,
Dana
Use Javascript to detect a change of the list. When a change occurs, you can make an AJAX request using a PHP script to return a new list. Javascript can manipulate the new data set and replace the DOM with the new appropriate list.
<script type=\"text/javascript\">
function changeCountry(){
var e = document.getElementById(\"country_id\");
var country_id = e.options[e.selectedIndex].value;
if(country_id == 1){
// Display states
document.getElementById('display_province').style.display = \"none\";
document.getElementById('display_state').style.display = \"\";
document.getElementById('display_state').style.visibility = \"visible\";
}
else{
// Display Province
document.getElementById('display_state').style.display = \"none\";
document.getElementById('display_province').style.display = \"\";
document.getElementById('display_province').style.visibility = \"visible\";
// Remove current selection list
var select = document.getElementById('province_id');
for (var option in select){
select.remove(option);
}
// Get Provinces for country_id
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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 xmlDoc = xmlhttp.responseXML;
// get each property
var x=xmlDoc.getElementsByTagName('province');
for (i=0;i<x.length;i++)
{
var e = document.getElementById('province_id');
var opt = document.createElement('option');
opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
e.appendChild(opt);
}
}
}
var url = 'get_provinces.php?country_id='+country_id;
// var url = 'provinces.xml';
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
}
}
function changeShippingCountry(){
var e = document.getElementById(\"shipto_country_id\");
var shipto_country_id = e.options[e.selectedIndex].value;
if(shipto_country_id == 1){
// Display states
document.getElementById('shipto_display_province').style.display = \"none\";
document.getElementById('shipto_display_state').style.display = \"\";
document.getElementById('shipto_display_state').style.visibility = \"visible\";
}
else{
// Display Province
document.getElementById('shipto_display_state').style.display = \"none\";
document.getElementById('shipto_display_province').style.display = \"\";
document.getElementById('shipto_display_province').style.visibility = \"visible\";
// Remove current selection list
var select = document.getElementById('shipto_province_id');
for (var option in select){
select.remove(option);
}
// Get Provinces for country_id
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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 xmlDoc = xmlhttp.responseXML;
// get each property
var x=xmlDoc.getElementsByTagName('province');
for (i=0;i<x.length;i++)
{
var e = document.getElementById('shipto_province_id');
var opt = document.createElement('option');
opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
e.appendChild(opt);
}
}
}
var url = 'get_provinces.php?country_id='+shipto_country_id;
// var url = 'provinces.xml';
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
}
}
function addProvince(){
// Get input
var np = document.getElementById('new_province').value;
// Get country_id
var e = document.getElementById(\"country_id\");
var country_id = e.options[e.selectedIndex].value;
// Erase input
document.getElementById('new_province').value = \"\";
// Add to database
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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 xmlDoc = xmlhttp.responseXML;
}
}
var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
changeCountry();
changeShippingCountry();
}
function addShippingProvince(){
// Get input
var np = document.getElementById('shipto_new_province').value;
// Get country_id
var e = document.getElementById(\"shipto_country_id\");
var country_id = e.options[e.selectedIndex].value;
// Erase input
document.getElementById('shipto_new_province').value = \"\";
// Add to database
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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 xmlDoc = xmlhttp.responseXML;
}
}
var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
changeShippingCountry();
changeCountry();
}
function hideShipping(){
document.getElementById('shipping').style.display = \"none\";
document.getElementById('shipping').style.visibility = \"hidden\";
}
function displayShipping(){
document.getElementById('shipping').style.display = \"\";
document.getElementById('shipping').style.visibility = \"visible\";
}
You can make an ajax call to an endpoint you set up that runs some php code and returns some JSON that your javascript can then use to populate the second list. Your javascript would look something like:
$.ajax( "your-endpoint.php" )
.done(function(data) {
// use javascript to dynamically populate your list
var json = data;
//assuming data is a list you could iterate over it
$.each(data, function (k, v) {
//use this to populate your list
}
})
.fail(function() {
// show an error message on your form
});
Your PHP endpoint would have to return a JSON object so that your javascript can more easily use it.
Communcation betwen php and javascript is typically done by Ajax, which is very simple to use in jQuery. The basic syntax is something like this:
$.ajax({
type: "POST",
url: "yourFile.php",
data: "{data: " + yourData + "}", //yourData is javascript variable
success: function(result){
//do something with result from php file
}
});
Where variable yourData is what you want to send to php script and it would be accessible throught $_POST['data'].
Everyone answered that Ajax is the solution, and I agree, Ajax is more elegant, but Ajax is not the only solution. I post this answer only to show another way to do it : without Ajax.
The first code (combos.php) is the page with a combo that, when selected, calls PHP. The second code (combos_action.php) is the PHP that returns the values according to the option selected. To make this codes to work, create two text files with the given names, copy-paste the codes and run it from your browser with http://localhost/combos.php. If you change the filenames, change them in the code, also.
Here is how it works : the page shows a simple combo filled with the days of the week. When a day is selected the JavaScript's onchange event fires and the form is autosubmitted, PHP gets the selected day and stores some values in session, returns to the page that refreshes and fills the second combo with those values. Comments will help you to understand:
combos.php
<?php
session_start(); // NECESSARY TO RETRIEVE THE VALUE RETURNED FROM PHP.
?>
<html>
<head>
<title>By José Manuel Abarca Rodríguez</title>
<script type="text/javascript">
// AUTOSUBMIT FORM #1 WHEN ANY OPTION IN COMBO #1 IS SELECTED.
function combo1_selected () {
document.getElementById( "form1" ).submit();
}
</script>
</head>
<body>
<!-- THIS IS COMBO #1. -->
<form id="form1" method="post" action="combos_action.php">
Select a day
<br/>
<select name="combo1" onchange="combo1_selected()"> <!-- NOTICE THE EVENT! -->
<option>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
</select>
</form>
<?php
// DISPLAY COMBO #2 ONLY IF COMBO #1 WAS SELECTED.
if ( isset( $_SESSION[ "combo2" ] ) )
{ echo "<br/>" .
"<br/>" .
"Options for <b>" . $_SESSION[ "combo1" ] . "</b>" .
"<br/>" .
"<select name='combo2'>";
// SEPARATE THE OPTIONS RETURNED FROM PHP.
$options = explode( ",",$_SESSION[ "combo2" ] );
// DISPLAY THE OPTIONS FOR THE COMBO.
for ( $i = 0; $i < count( $options ); $i++ )
echo "<option>" . $options[ $i ] . "</option>";
echo "</select>";
}
?>
</body>
</html>
combos_action.php
<?php
session_start();
$_SESSION[ "combo1" ] = $_POST[ "combo1" ]; // SELECTED OPTION.
if ( $_SESSION[ "combo1" ] == "Monday" )
$_SESSION[ "combo2" ] = "mon 1,mon 2,mon 3"; // RETURN THESE VALUES.
if ( $_SESSION[ "combo1" ] == "Tuesday" )
$_SESSION[ "combo2" ] = "tue 1,tue 2,tue 3"; // RETURN THESE VALUES.
if ( $_SESSION[ "combo1" ] == "Wednesday" )
$_SESSION[ "combo2" ] = "wed 1,wed 2,wed 3"; // RETURN THESE VALUES.
header( "Location: combos.php" ); // RETURN TO PAGE.
?>
Related
I'm stuck..I have made a system which gets all colleges from a specific subject, and I want javascript to select the college the user has selected when he clicks on one so the presence of that class can be shown, just a summary: the user selects a subject, an AJAX request gets all colleges from that subject and another AJAX request has to get that specific college and use it to display the data.
This specific function gets the data from the subjects and displays them in a div with the id 'colleges'
function showAanwezigheid(str) {
if (str == "") {
document.getElementById("colleges").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("colleges").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../controller/docentController.php?action=getColleges&vak="+str,true);
xmlhttp.send();
}
}
Here is the controller which calls the query and displays the result:
$vak = $_GET['vak'];
$colleges = $q->getColleges($vak);
echo "<select id='college'>";
echo "<option>Selecteer een college:</option>";
foreach($colleges as $college){
echo "<option value='".$college->getCollege()."'>College ".$college->getCollege()."</option>";
}
echo "</select>";
}
This is the id where the result is being displayed
<span id="colleges"></span>
And this function should select the 'select' tag with the id 'college' to get that value on change
$(document).ready(function(){
$('#vak').on('change', function() {
var vak = this.value;
alert(vak);
$('#college').on('change', function() {
var college = this.value;
alert(college);
});
});
});
I feel like there would be such an easy fix but I just can't seen to make it work...
Change jQuery code like below:-
$(document).on('change','#vak',function() {
var vak = $(this).val();
alert(vak);
});
$(document).on('change','#college',function() {
var college = $(this).val();
alert(college);
});
Note:- Make sure that jQuery library added before your script code. Otherwise you will get $ is undefined error
This is called Event Delegation
IF you want to get the value of the #college select on change then this would be simpler:
$(document).ready(function(){
$('#vak').on('change', function() {
var vak = $(this).val();
alert(vak);
});
$('#college').on('change', function() {
var college = $(this).val();
alert(college);
});
});
IF you noticed, The onchange of the #vak and the #college is separated
I've been trying to get this solved for 2 weeks now and still have no success.
JavaScript:
var quotenum = 0;
var xmlhttp = null;
var rt = "";
function ChangeQuote() {
quotenum++;
xmlhttp = null;
//alert("quotenum= "+quotenum);
if (quotenum === 0) {
document.getElementById("quote").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 === XMLHttpRequest.DONE && xmlhttp.status === 200) {
rt = xmlhttp.responseText;
//alert("quote= "+rt);
alert("request number= " + xmlhttp.length);
document.getElementById("quote").innerHTML = rt;
}
};
xmlhttp.open("Get", "getquote.php?q=" + quotenum, false);
//xmlhttp.open("GET", "getquote.php?XDEBUG_SESSION_START=netbeans-xdebug&q=" + quotenum, false);
xmlhttp.send();
//var thediv = document.getElementById("quote");
return false;
}
PHP:
error_reporting(E_ERROR | E_PARSE);
$q="";
$q = intval($_GET['q']);
$link=mysqli_connect("localhost","root","sequence","babylon");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="SELECT quotetext FROM quote where quotenum='".$q."'";
$show=mysqli_query($link,$query) or die ("Error");
while($row=mysqli_fetch_array($show)){
echo $row["quotetext"];
}
Can anyone see anything wrong with this?
Using WAMP I can see the correct result when I run the PHP file in a browser.
I also try to use Jquery instead.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var quotenum = 0;
// var xmlhttp = null;
// var rt = "";
function ChangeQuote() {
quotenum++;
$.ajax({
url: "getquote.php?q="+quotenum,
method: "get",
data: {
q: quotenum
}
}).done(function (data) {
alert(data);
document.getElementById("quote").innerHTML = data.quotetext;
});
return false;
}
</script>
The only noticable error I see is you inlining your js with the script tag that has a src attribute.
HTML 4.01 Specification:
The script may be defined within the
contents of the SCRIPT element or in
an external file. If the src attribute
is not set, user agents must interpret
the contents of the element as the
script. If the src has a URI value,
user agents must ignore the element's
contents and retrieve the script via
the URI.
I have a document on PHP retrieving the postal codes via form and it gives back an array. If the postal code is used on more than one citie, it creates a multidimensional array, otherwise it stores everything just in one.
I have three scenarios:
If the postal code doesn't exist it gives an array with 2 values "Doesn't exist" and output it on the form.
If the postal code exists it gives you an array with the city and the state and output them on the form.
If the postal code exists and is used on more than one citie it stores every result on an array and all of them into a another array (Array => Array [0] => Array([city]=>city1 [state]=>state1) Array [1] => Array([city]=>city2 [state]=>state2)... and then outputs a popup.
I managed to do everything but I still have some problems. Here's my code:
Script PHP
include_once('../../../connect.html');
//perform lookup
$title = ($_GET['postal_code']);
$statement = $connection->prepare ("SELECT city, state FROM cities, states WHERE cities.state_id = states.state_id AND cities.postal_code = ?");
$statement->execute(array($title));
$statement->setFetchMode(PDO::FETCH_ASSOC);
$items = array();
while ($r = $statement->fetch()) {
//$arrayName = array($r = $statement->fetch());
$items[] = $r;
}
if (count($items) == '1'){
$newArray = $items[0];
echo $newArray['city'].",".$newArray['state'];
}elseif (count($items) == '0'){
echo "Doesn't exist".","."Doesn't exist";
}else{
$varios = array($items);
print_r($varios);
}
AJAX code
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var zipValue = document.getElementById("postal_code").value;
if(zipValue)
{
var url = "get_cities.php";
var param = "?postal_code=" + escape(zipValue);
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
if( ajax.responseText.length ) {
if (ajax.responseText[2]) {
centerPopup();
loadPopup();
}
citystatearr = ajax.responseText.split(",");
city.value = citystatearr[0];
state.value = citystatearr[1];
}else{
}
}
}
Problems are:
It calls the function centerPopup and loadPopup everytime, regardless the result (it should be called only when the PHP script gives back a multidimensional array.
I don't know how to detect via AJAX when the script is sending the normal array or the multidimensional array.
It's basically those two problems but solving one, the other one is solved.
Any help is appreciated!!
ajax.responseText is a string, in JavaScript string[n] return the nth letter of the string.
You must encode your data in PHP then decode it in JavaScript, the best way to do it is with JSON. Both PHP and JavaScript provide support for JSON (json_encode/json_decode and JSON.stringify/JSON.parse) so it's easier!
So this is the code in JS:
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var zipValue = document.getElementById("postal_code").value;
if(zipValue)
{
var url = "get_cities.php";
var param = "?postal_code=" + escape(zipValue);
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
if( ajax.responseText.length ) {
try {
var data = JSON.parse(ajax.responseText); // = $items
}
catch(e) {
//json parse error
}
if (data[2]) {
centerPopup();
loadPopup();
}
citystatearr = ajax.responseText.split(",");
// ^^^^^^ I think you'll need to change this
city.value = citystatearr[0];
state.value = citystatearr[1];
}else{
}
}
}
And PHP :
include_once('../../../connect.html');
//perform lookup
$title = ($_GET['postal_code']);
$statement = $connection->prepare ("SELECT city, state FROM cities, states WHERE cities.state_id = states.state_id AND cities.postal_code = ?");
$statement->execute(array($title));
$statement->setFetchMode(PDO::FETCH_ASSOC);
$items = array();
while ($r = $statement->fetch()) {
//$arrayName = array($r = $statement->fetch());
$items[] = $r;
}
if (count($items) == '1'){
$newArray = $items[0];
echo $newArray['city'].",".$newArray['state'];
}elseif (count($items) == '0'){
echo "Doesn't exist".","."Doesn't exist";
}else{
$varios = array($items);
die(json_encode($varios));
}
I am new to javascript, am using PHP variable for created link dynamically as given below
$addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart('.#$product_id.',"add")><span class="allitem"
<font color="#A2F3AB">Added</font></span></button>';
This my php variable created by dynamically like below.
Added
Added
Added
I want to change the content of all variable“ added” as“ add” by just one click,Am using ajax function for changing that text as given below..
function clearcart(msg) {
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('cartreturn').innerHTML = xmlhttp.responseText;
document.getElementsByClassName('allitem').innerHTML = "Add";
}
}
xmlhttp.open("GET", "/addcart.php?msg=" + msg, true);
xmlhttp.send();
}
But first link text only affected.. other is not affected how I can solve this problem
document.getElementsByClassName returns a NodeList. You have to iterate over all the elements:
var allItems = getElementsByClassName('allitem');
for (var i = 0; i < allItems.length; i++) {
allItems[i].innerHTML = 'Add';
}
See this question.
You can't do document.getElementsByClassName('allitem').innerHTML.
You can do document.getElementsByClassName('allitem')[0].innerHTML = "Add"
Do you have several elements with the class "allitem"? If you don't, then maybe you should use an id, instead of a class, and then call document.getElementById('allitem').innerHTML = "Add";
Once a dropdown list option is selected, I would like to hold that selected option as a javascript variable.
To make this a little more complex, the variable should be held inside the page's main Ajax coding, so it is not lost when different Ajax content is loaded.
Here's my wonderfully basic form code:
<form name="searchLocations" method="POST">
<select name="locationName">
<?php
$sql = mysql_query("SELECT locationName FROM tbl_locations ORDER BY locationName ASC");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['locationName'] . "</option>";
}
?>
</select>
<button onclick="loadXMLDoc(indexSearchingSubmit);" id="searchingSubmit">Search</button>
</form>
and here is my main ajax code, where the form dropdown variable should be held so it can be used later:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
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("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
Using jQuery:
$('[name="locationName"]').change(function() {
YOUR_VAR = $(this).attr('value');
});
Not using jQuery-
Add onChange() to your SELECT element, also added id attribute.
Add javascript onchange handler function, which just retrieves the selected value and sets your var
<select name="locationName" onChange="setSelected()" id="locationSelect">
function setSelected(){
var myselect= document.getElementById("locationSelect");
YOUR_VAR = myselect.options[myselect.selectedIndex].value;
}