Changing URL after selecting value from dropdown menu - javascript

I have a HTML form with two dropdown menus. First dropdown is prepopulated from database with PHP, second one is linked with first one and uses AJAX to update values according to the selection from first one.
How can I make the URL to change after selecting something from the dropdown menu? E.g. after selecting something from first dropdown, URL would be something like http://myurl.com/form.php/option1 and after second choice http://myurl.com/form.php/option1+option2.
My code:
Scripts:
<script>
function kuvaRingkond(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","getringkond.php?q="+str,true);
xmlhttp.send();
}
}
</script>
function AjaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Teie brauser ei toeta Ajaxit!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
var myarray = JSON.parse(httpxml.responseText);
// Remove the options from 2nd dropdown list
for(j=document.form.kandidaat.options.length-1;j>=0;j--)
{
document.form.kandidaat.remove(j);
}
var optn = document.createElement("OPTION");
optn.text = 'Vali kandidaat';
optn.value = '0';
document.form.kandidaat.options.add(optn);
for (i=0;i<myarray.data.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].Eesnimi + ' ' + myarray.data[i].Perekonnanimi;
optn.value = myarray.data[i].KandidaadiID;
document.form .kandidaat.options.add(optn);
}
}
}
// end of function stateck
var url="dd.php";
var erakond_id=document.getElementById('s1').value;
url=url+"?erakond_id="+erakond_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
Form:
<form role="form" name="form" method="POST" action="haaletamine_form.php">
<div class="form-group">
<label for="erakond">
Erakond:
</label>
<?php
require "connection_pdo.php";// connection to database
echo "<select class ='form-control' name=erakond id='s1' onchange=AjaxFunction();>";
echo "<option selecter='selected'>Vali erakond</option>";
$sql="select * from erakonnad "; // Query to collect data from table
foreach ($dbo->
query($sql) as $row) {
echo "<option value=$row[ErakonnaID]>$row[ErakonnaNimi]</option>";
}
echo "</select>";
?>
</div>
<div class="form-group">
<label for="kandidaat">
Kandidaat:
</label>
<select class="form-control" name=kandidaat id='s2' onchange="kuvaRingkond(this.value)">
<option selecter="selected">
Vali kandidaat
</option>
</select>
</div>
<div id="txtHint">
<b>
</b>
</div>
<button type="submit" class="btn btn-default">
Kinnita valik
</button>
</form>
Thanks!

This is how I would do it.
HTML
<select id="select-list">
<option>Option One</option>
<option>Option Two</option>
<option>Option Three</option>
</select>
jQuery
$(document).ready(function() {
$('#select-list').on('change', function() {
var nSelectOption = $('#select-list').find(':selected').text();
switch(nSelectOption) {
case "Option One":
window.location.href = 'http://google.com';
break;
case "Option Two":
window.location.href = 'http://google.com';
break;
case "Option Three":
window.location.href = 'http://google.com';
break;
}
});
});

Related

dependent drop downlist generation

I'm trying to make a dependent dropdown list using ajax and php but not able to get the desired result
here is my code of ajax
<html>
<head>
<title>findperson</title>
<script type="text/javascript">
function configureDropDownLists(ddl1,ddl2) {
var x=ddl1.value;
var service;
var url='service.php?data='+x;
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET",url);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
service=XMLHttpRequestObject.responseText;
for (var i=0;i<service.length;i++ ){
var opt = service[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
ddl2.appendChild(el);
}
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<form method="post" action="problem.php">
<select name="city" id="city" onchange="configureDropDownLists(this,document.getElementById('service'))">
<option selected="selected" value="">City</option>
<option value="jhansi">Jhansi</option>
<option value="lucknow">Lucknow</option>
</select>
<select id="service">
<option selected="selected" value="">Service</option>
</select>
<input type="submit" name="proceed" value="Next"/>
</form>
</body>
</html>
this is my php file
<?php
include_once('db.php');
$db=new db();
$sql=$db->database_initialise();
$city=$_GET['data'];
$query="select service_name from service_offered where city='$city'";
if($result=$sql->query($query)){
if($result->num_rows >0){
$i=0;
while($row=$result->fetch_array()){
$service[$i]=$row[0];
$i++;
}
}
}
var_dump($service);
?>
problem is that in second dropdown list no changes occur on selecting a city
Replace var_dump($service)
echo json_encode($service);
A couple of problems here:
your PHP is not sending the correct response. What you want to do is have PHP send a JSON response.
once PHP sends this JSON response, you then need to parse this into an object
Once your response is in object format, you can then iterate through the results.
Try this:
PHP (this is an example of what will be returned from your DB):
$response = array(
array(
"id" => "1",
"name" => "something"
)
);
header('Content-Type: application/json');
echo json_encode($response);
JS:
function configureDropDownLists(ddl1, ddl2) {
var url = 'submit.php?data=' + ddl1.value;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = xmlhttp.responseText;
var obj = JSON.parse(json);
for (var i = 0; i < obj.length; i++) {
var opt = obj[i];
var el = document.createElement("option");
el.textContent = opt.name;
el.value = opt.id;
ddl2.appendChild(el);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
Your issue is that you are returning the $service array from your PHP and accessing it in your AJAX as a string. service=XMLHttpRequestObject.responseText; returns a string object. In your for loop it looks like you are trying to index through an array. However, you can't index through a string like that and get what you are expecting.
The best thing is to use echo json_encode($service); like Leo suggested, then in your AJAX transform the responseText by using JSON.parse
var json = JSON.parse(XMLHttpRequestObject.responseText);
Then in the for loop
var opt = json[/*i or column name*/];
or
var opt = json.service_name[i];
Note: To return a JSON string in PHP, you have to set the header: header("Content-type: application/json");
Hope that helps!

send two values to ajax query

I need to send two parameter to my javascript and get the parameters in the php file how I can do it ?
My html :
<form method="post" action="testButtonSup.php">
<p>
Veuillez choisir le service<br />
<input type="radio" name="service" value="ncli" id="ncli" checked ="checked" /> <label for="ncli">Ncli</label>
<input type="radio" name="service" value="fcli" id="fcli" /> <label for="fcli">Fcli</label>
</p>
<p>
<label for="client">Veuillez choisir le fournisseur :</label><br />
<select name="client" id="client" onchange="showUser(this.value, service)">
<?php
// echo '<option value=""/></option>';
while ($donnees = $reponse->fetch())
{
echo '<option value='.$donnees['refCustomer'].'>'.$donnees['legalCompanyName'].' </option>';
$idClient = $donnees['refCustomer'];
//$value = $donnees['refCustomer'];
}
$reponse->closeCursor();
?>
</select>
</p>
<p>.....
I want to send to the function showUser(this.value, service) two parameters
: the id of the select and the value of the radio button "service" whic is up
My function :
function showUser(str, service) {
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","getTableBuffer.php?q="+str+"&service="service,true);
xmlhttp.send();
}
}
I tried like this but it doesn't work.
in my php file it didn't recognize the parameter.
It works with only the id of the select.
Without jQuery, a smallish function to get the value of a radio button from the collection to use in the ajax parameters.
function radiovalue(name){
var col=document.querySelectorAll('input[type="radio"]');
for( var n in col )if( n && col[n] && col[n].nodeType==1 && col[n].type=='radio' ){
if( col[n].hasAttribute('name') && col[n].getAttribute('name')==name ){
if( col[n].checked ) return col[n].value;
}
}
return false;
}
eg:
---
xmlhttp.open("GET","getTableBuffer.php?q="+str+"&service="+radiovalue('service'),true);
If you can use jQuery (which I recommend to handle ajax request) you can do it this way:
function showUser(str, service) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
$.ajax({
url: 'getTableBuffer.php',
type: 'GET',
data: {q:str, service:service}
}).done(function(response){
// Code to execute once the call has been executed
$('#txtHint').html(response.responseText);
});
}
}

How to show results with AJAX

I have problem with AJAX and database. I don't know what I have now to do.
So, I have this AJAX code:
<script>
function showCity(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","rozpiski.php?q="+str,true);
xmlhttp.send();
}
}
</script>
I want:
When user select some option, the second select list shows value (after gets this values from database).
This is my code HTML:
<select name="country3" onchange="showCity(this.value)"> <option>Anglia</option><option selected='selected'>Austria</option><option>Belgia</option><option>Czechy</option><option>Dania</option><option>Estonia</option><option>Finlandia</option><option>Francja</option><option>Holandia</option><option>Islandia</option><option>Lichtenstein</option><option>Luxembourg</option><option>Niemcy</option><option>Norwegia</option><option>Polska</option><option>Szwajcaria</option><option>Szwecja</option><option>Słowacja</option><option>Słowenia</option><option>Wyspy Owcze</option><option>Węgry</option><option>Włochy</option><option>Łotwa</option><option>Anglia</option><option>Austria</option><option>Belgia</option><option>Czechy</option><option>Dania</option><option>Estonia</option><option>Finlandia</option><option>Francja</option><option>Holandia</option><option>Islandia</option><option>Lichtenstein</option><option>Luxembourg</option><option>Niemcy</option><option>Norwegia</option><option>Polska</option><option>Szwajcaria</option><option>Szwecja</option><option>Słowacja</option><option>Słowenia</option><option selected='selected'>Wyspy Owcze</option><option>Węgry</option><option>Włochy</option><option>Łotwa</option><option>Anglia</option><option>Austria</option><option>Belgia</option><option>Czechy</option><option>Dania</option><option>Estonia</option><option>Finlandia</option><option>Francja</option><option>Holandia</option><option>Islandia</option><option>Lichtenstein</option><option>Luxembourg</option><option>Niemcy</option><option>Norwegia</option><option>Polska</option><option>Szwajcaria</option><option>Szwecja</option><option>Słowacja</option><option>Słowenia</option><option>Wyspy Owcze</option><option>Węgry</option><option>Włochy</option><option>Łotwa</option></select></td>
<td><select name="city" id="3"></select>
When the user in country3 select for example Polska, he gets in 2nd select cities from Polska. This cities are in database. How to do it?
Your html select-option tags should be:
<select name="country3" onchange="showCity(this.value)">
<option value="city">City</option>
</select>

in 3 dependent box, 3rd box is not populating value using ajax and vbscript in asp classic

I am populating 3(triple) dependent box using ajax and vbscript in asp classic page. 1st and 2nd boxes working ok. if i select STATE in 1st box then, in 2nd box CITY list is populating but when i select 2nd box (CITY), in 3rd box CENTER list is not populating.
my ajax script as below given:
<script language="javascript" type="text/javascript">
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=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(stateId) {
var strURL="findcity1.asp?state="+stateId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
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);
}
}
function getCenter(StateId,CityId) {
var strURL="findCenter.asp?state="+stateId+"&city="+cityId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('centerdiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
My code for populating STATES, CITY AND CENTER as below given
<%
dim Objrs_state, str_state, objCmd_state
Set objCmd_state = Server.CreateObject("ADODB.Command")
Set Objrs_state = Server.CreateObject("ADODB.Recordset")
str_state = "SELECT ASId, ASName FROM State_Name ORDER BY ASName Asc"
With objCmd_state
.ActiveConnection = MM_connDUdirectory_STRING
.CommandText = str_state
.CommandType = adCmdText
end with
Objrs_state.open objCmd_state, , 1, 2
%>
<select name="statid" onChange="getcity(this.value)">
<option>Select State</option>
<%while not Objrs_state.eof%>
<option value="<%=Objrs_state("ASId")%>"><%=Objrs_state("ASName")%></option>
<%Objrs_state.movenext
wend
Objrs_state.close
set Objrs_state = nothing
set objCmd_state = nothing%>
</select>
'populating CITY as below given
<span id="citydiv"><select name="city">
<option>Select City</option>
</select></span>
'populating CENTER as below given
<span id="centerdiv"><select name="center">
<option>Select Center</option>
</select></span>
FindCity.asp
Set objCmd = Server.CreateObject("ADODB.Command")
Set Objrs = Server.CreateObject("ADODB.Recordset")
str = "SELECT * FROM city_Name where ASId =? ORDER BY ACName Asc"
....
....
<select name="city" onChange="getcenter(stateID,this.value)">
<option>select city</option>
<% Do While Not Objrs.EOF %>
<option value="<%=objrs("ACId")%>"><%= Objrs("ACName")%></option>
<%
Objrs.MoveNext
Loop
%>
</select>
FindCenter.asp page
Set objCmd = Server.CreateObject("ADODB.Command")
Set Objrs = Server.CreateObject("ADODB.Recordset")
str = "SELECT * FROM Center_Detail where Center_state=? and Center_city=? ORDER BY Center_Name Asc"
....
....
<select name="center">
<option>select center</option>
<% Do While Not Objrs_center.EOF %>
<option value="<%=objrs_center("CnId")%>"><%= Objrs_center("Center_Name")%></option>
<%
Objrs_center.MoveNext
Loop
%>
</select>
1st and 2nd box populating and working fine but in 3rd box center list related to select city is not showing. Please help me out to solve this issue.

2 select menu filters with Jquery disable, pass values to one function

I have 2 select menus whose values i want to get passed to a function.
I am trying to use jquery to disabled the 2nd select until the first one is selected.
I am having 2 issues with this:
My jquery does not seem to want to disable the 2nd select menu.
Also how can i pass the 1st select menu value to the onchange
function value in the second select menu.
Thanks in advance
Function
function showlog(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", "getlog.php?username=" + username + "&q=" + str, true);
xmlhttp.send();
}
JQUERY
$(document).ready(function() {
var linkOrder = [
"employee_user",
"acyear"
];
$('select.linked').not('#' + linkOrder[0]).attr('disabled', 'disabled');
$('.linked').change(function() {
var id = $(this).attr('id');
var index = $.inArray(id, linkOrder);
$('#' + linkOrder[index + 1]).removeAttr('disabled');
});
});
FORM
<form>
<select id="employee_user" name="employee_user" class="linked">
<option value="">Select</option>
</select>
<select id="acyear" name="acyear" onchange="showlog(this.value, 1st select value" class="linked">
<option value=""></option>
</select>
</form>

Categories

Resources