Need Help On Ajax - php

I am trying to use an ajax function when the form's select value has changed. It should display a list of cities based on the selected state. However, it is not doing anything.
cities.php
<script type="text/javascript">
function change_state(str)
{
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("cityselector").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","changestate.php?changed_state="+str,true);
xmlhttp.send();
}
</script>
<div class="city-switcher">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get" id="cityselector" style="position: absolute; top: 15px; left: 310px;">
<select name="city" onchange="document.forms['cityselector'].submit()" style="font-size: 1.5em;">
<?php
$selected_state = select_single("STATE", "locations", "NAME='$location'", "");
$cities = select("*", "locations", "STATE='$selected_state'", "");
foreach ($cities as $city){
echo '<option value="'.$city['NAME'].'" '.($location == $city['NAME'] ? 'selected="selected"' : '').'>'.$city['NAME'].'</option>';
}
?>
</select>
</form>
<select name="state" onchange="change_state(this.value)" style="font-size: 1.5em;">
<?php
$states = select("DISTINCT STATE", "locations", "", "ORDER BY STATE ASC");
$selected_state = select_single("STATE", "locations", "NAME='$location'", "");
foreach ($states as $state){
echo '<option value="'.$state['STATE'].'" '.($selected_state == $state['STATE'] ? 'selected="selected"' : '').'>'.$state['STATE'].'</option>';
}
?>
</select>
</div>
changestate.php
<?php
include '../config.php';
include '../library.php';
$changed_state = $_GET['changed_state'];
echo '<select name="city" onchange="document.forms[\'cityselector\'].submit()" style="font-size: 1.5em;">';
$cities = select("*", "locations", "STATE='$changed_state'", "");
foreach ($cities as $city){
echo '<option value="'.$city['NAME'].'" '.($location == $city['NAME'] ? 'selected="selected"' : '').'>'.$city['NAME'].'</option>';
}
echo '</select>';
?>
Can anyone tell me what I'm doing wrong.
Thanks,

After Rereading i am modifying my answer
<select name="state" onchange="change_state(this.value)"
should be
<select ... onchange="change_state(this.options[this.selectedIndex].value)" ...

Figured out the problem. The problem was that my path was wrong for xmlhttp.open("GET","changestate.php?changed_state="+str,true);
Instead it should be
xmlhttp.open("GET","sections/changestate.php?changed_state="+str,true);

Related

Values returned but not populated on select

I have next scripts:
test.php - in header I have:
<script>
function dest(str2) {
if (str2 == "") {
return;
} else {
//alert(str2);
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("destin").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","dest.php?q2="+str2,true);
xmlhttp.send();
}
}
</script>
test.php - in body I have:
<div class="col-sm-12">
<div class="form-group has-icon has-label selectpicker-wrapper">
<label>De la</label>
<?php
$plecari=db_query("SELECT DISTINCT plecare from `pl_dest_pf` WHERE activ = 'activ' ORDER BY plecare");
?>
<select class="selectpicker input-price" data-live-search="true" data-width="100%" data-toggle="tooltip" title="Select" name="plecare" id="dela" onchange="dest(this.value)">
<?php
while($rez_plecari = $plecari->fetch_assoc()){
?>
<option value="<?php echo $rez_plecari['plecare']?>"><?php echo $rez_plecari['plecare']?></option>
<?php } ?>
</select>
<span class="form-control-icon"><i class="fa fa-location-arrow"></i></span>
</div>
</div>
<div class="col-sm-12">
<div class="form-group has-icon has-label selectpicker-wrapper">
<label>Pana la </label>
<select id="destin" class="selectpicker input-price" data-live-search="true" data-width="100%" data-toggle="tooltip" title="Select" name="desti">
</select>
<span class="form-control-icon"><i class="fa fa-location-arrow"></i></span>
</div>
</div>
dest.php:
<?php
session_start();
include('include/functions2.php');
$a=$_GET['q2'];
$destinatie=db_query("SELECT DISTINCT destinatie from `pl_dest_pf` WHERE plecare ='".$a."' AND activ = 'activ' ORDER BY destinatie ");
?>
<option value="">Selecteaza...</option>
<?php
while($rez_destinatie = $destinatie->fetch_assoc()){
?>
<option value="<?php echo $rez_destinatie['destinatie']?>"><?php echo $rez_destinatie['destinatie']?></option>
<?php } ?>
My issue is that the values for 2nd select are returned, but not showed on 2nd select (I can see it only with alert command).
May you please tell me where I have the mistake.
Many thanks!

Store the drop down selected value in a SESSION variable

Im getting a set of values from the database to show in a drop down list. Once the user selected an item from the drop down list the selected item should be assigned to a SESSION variable. I tried this but yet it is not working. Please smeone help me to sort it out.
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "><option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result)){
echo "<option value='$row[Form_ID]'>$row[Form_Name]</option>";
echo
}
?>
</select>
So I need to store these values receive from $row[Form_ID] and $row[Form_Name] in 2 session variables named $_SESSION['Form_ID'] and $_SESSION['Form_Name']; Could someone explain me how I can assign the selected item's values to these two session variables.
The selected option element must have selected attribute.
You should try something like this:
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; ">
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result))
{
echo "<option value='{$row['Form_ID']}'";
if($row['Form_ID'] == $_SESSION['Form_ID'])
echo " selected";
echo ">{$row['Form_Name']}</option>";
}
?>
</select>
UPDATE:
You can store it in $_SESSION after the form submit
<?php
session_start(); // dont forget it!
if(isset($_POST['submit']))
{
$_SESSION['Form_ID'] = $_POST['Form_ID'];
$_SESSION['Form_Name'] = $_POST['Form_Name'];
}
?>
Try This:
In your page add this and create one more page "showValues.php"(This is the page where you want to create and use your session variable).Code of showValues.php is also given below for example.
<html>
<head>
<script>
function showValue(vals)
{
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 val= xmlhttp.responseText;
document.getElementById("tbl").innerHTML+=val;
}
}
xmlhttp.open("GET","showValues.php?vals="+vals,true);
xmlhttp.send();
}
</script>
</head>
<body>
<table id="tbl">
<tr>
<td>
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "><option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result)){
echo "<option value='$row[Form_ID]'>$row[Form_Name]</option>";
echo
}
?>
</select>
</td>
</tr>
</table>
</body>
</html>
showValues.php
<?php
session_start();
$vals=$_REQUEST['vals'];
$_SESSION['SelectValue']=$vals;
echo $_SESSION['SelectValue'];
?>
try this
<form name="my_name" method="POST" action="">
<select name="FormNameSelecting" id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "> //don't forget put name at select
<option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_assoc($result)){ //prefer using assoc that array
echo "<option value='" . $row['Form_ID'] . ":::" . $row['Form_Name'] . "'>" . $row['Form_Name'] . "</option>";
}
?>
</select>
<input type="submit" name="go" value="go"/>
</form>
<?php
if(isset($_POST['go'])){
$store_sesi = explode(":::",$_POST['FormNameSelecting']);
$_SESSION['ID'] = $store[0];
$_SESSION['Name'] = $store[1];
}
?>
hope this code help you

Ajax pulling information from second select and database

I want to have multiple drop down lists that perform a search in the database and echo the information in a table on the webpage.
From tutorials I have managed this, but only for one select choice. I am struggling to make the second drop down list refine the search conditions.
Drop down list 1 should be the option that searches the database for the selected value.
Drop down list 2 should add an AND condition to the sql and uses the second value to refine the search.
The code below does not pull any info from the database on change. If I remove the AND statement it will pull information from the database.
HTML:
<!DOCTYPE html>
<html>
<head>
<title> Vault of Faults-Fault Search </title>
<link rel="stylesheet" type="text/css" href="mystyle1.css">
<script src="dropdownfix1.js"></script>
</head>
<body>
<div id=container>
<div id=header>
<div id=headdiv>
<form id=login name="login" action="login.php" method="post">
<fieldset class="field_set">
<legend>Administrator Login:</legend> <!-- legeng tage creates a header title for the fieldset box, filedset pulls all data in the tag to gether with a box around it. -->
UserName: <input type="text" name="username"> <br>
Password:<br> <input type="password" name="password"> <br>
<input type="submit" value="Login"> <input type="Button" onClick="parent.location='addafix.php'" Value="Add a Fix">
</fieldset>
</form>
</div>
</div>
<div id=content>
<div id=maincontent>
<div id=select>
<form>
<fieldset class="field_set2">
<legend>Quicklink Vault of Faults Search</legend>
Product:
<select name="Product" onchange="showUser(this.value)">
<option value="0">Select Product</option>
<option value="1">Merlin</option>
<option value="2">Encoder</option>
<option value="3">Mac Live</option>
<option value="4">Windows Live</option>
<option value="5">Windows S&F</option>
<option value="6">Mac S&F</option>
</select>
<select name="Product_Issue" onchange="showIssue(this.value)">
<option value="0">Select Issue</option>
<option value="1">Preview</option>
<option value="2">Live Reciever</option>
<option value="3">Mac Live</option>
<option value="4">Windows Live</option>
<option value="5">Windows S&F</option>
<option value="6">Mac S&F</option>
</select>
<input type="submit" value="Search">
</fieldset>
</form>
</div>
<div id=list>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</div>
</div>
</div>
</div>
</body>
</html>
JavaScript:
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();
}
function showIssue(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?p="+str,true);
xmlhttp.send();
}
PHP:
<?php
$q=$_GET["q"];
$p=$_GET["p"];
require 'connection.php';
mysqli_select_db($con,"Faults" );
//where statement in the sql syntax will select where in db to get infor, use AND to add another condition
$sql="SELECT Products.Product_Name, Versions.Version, Platform.Platform_Name, Issues.Issue, Issues.Sub_Issue, Issues.Fix
FROM Solutions INNER JOIN Products ON Solutions.Product = Products.Product_id
INNER JOIN Versions ON Solutions.Product_Version = Versions.Version_id
INNER JOIN Platform ON Solutions.Product_Platform = Platform.Platform_id
INNER JOIN Issues ON Solutions.Product_Issue = Issues.Issue_id
WHERE Product = '".$q."' AND Product_Issue = '".$p."'";
$result = mysqli_query($con,$sql);
//below is the echo statment to create the results in a table format, list collumn titles
echo "<table id=tables border='1'>
<tr>
<th>Products</th>
<th>Version</th>
<th>Platform</th>
<th>Issue</th>
<th>Sub Issue</th>
<th>Fix</th>
</tr>";
//below is script to list reults in a table format, $row [row name on table]
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Product_Name'] . "</td>";
echo "<td>" . $row['Version'] . "</td>";
echo "<td>" . $row['Platform_Name'] . "</td>";
echo "<td>" . $row['Issue'] . "</td>";
echo "<td>" . $row['Sub_Issue'] . "</td>";
echo "<td>Fix</td>";
echo "</tr>";
}
echo "</table>";
// below closes the coonection to mysql
?>
I think you need to concat the values of the dropdownlist. Something like:
<script type="text/javascript">
function server(aform)
{
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+ product.value +"&" +"p="+product_i.value ,true);
xmlhttp.send();
}
</script>

how do i fill text box field with ajax

I have a combobox and i want to fill the State and Zip_code Field..its working but it fills each field State "NY11715" and Zip_code "NY11715"...i'm looking to fill State "NY" and Zip_code 11715...please help me resolve this
<select name="LookupCity" id="LookupCity" onchange="showZip(this.value)">
<option value="" <?php if (!(strcmp("", $_GET['City']))) {echo "selected=\"selected\"";} ?>>Select from menu</option>
<?php do { ?>
<option value="<?php echo $row_fmCity['City']?>"<?php if (!(strcmp($row_fmCity['City'], $_GET['City']))) {echo "selected=\"selected\"";} ?>><?php echo $row_fmCity['City']?></option>
<?php
} while ($row_fmCity = mysql_fetch_assoc($fmCity));
$rows = mysql_num_rows($fmCity);
if($rows > 0) {
mysql_data_seek($fmCity, 0);
$row_fmCity = mysql_fetch_assoc($fmCity); } ?> </select>
select</td>
</tr><tr valign="baseline">
<td nowrap="nowrap" align="right">State:</td>
<td><input type="text" name="State" id="State" placeholder="NY" value="<?php echo $_GET['State']; ?>" size="5"/>
<input type="text" name="Zip_Code" id="Zip_Code"placeholder="zip code" value="<?php echo $_GET['Zip']; ?>" size="10" /></td>
Ajax code
function showZip(str)
{
if (str=="")
{
document.getElementById("State").innerHTML="";
document.getElementById("Zip_Code").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("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Getzip.php?q="+str,true);
xmlhttp.send();
}
PHP Code
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Leadbook", $con);
$sql="SELECT * FROM Zip WHERE City = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$State = $row['State'];
$Zip_Code = $row['Zip Code'];
}
echo $State;
echo $Zip_Code;
mysql_close($con);
?>
1. change your php code, so that both city and zip code are comma seperated.
change this code:
echo $State;
echo $Zip_Code;
to this:
echo $State;
echo ",";
echo $Zip_Code;
2. than update your javascript, so that the return text is splitted into 2 parts and gets to its respected fields.
change this code:
document.getElementById("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
to this:
var string = xmlhttp.responseText;
var array = string.split(',');
document.getElementById("State").value=array[0];
document.getElementById("Zip_Code").value=array[1];
this should do what you requested.

Issue With the Ajax's derived Selection box

<script type="text/javascript" src="jquery-1.js"></script>
<style type="text/css">
div {
height:25px;
}
label {
text-align:left;
width:100px;
display:inline-block;
vertical-align:top;
}
input {
margin-right:5px;
}
</style>
<script type="text/javascript">
//<![CDATA[
$(window).load(function(){
// $('select').toggle();
$('input').click(function(event) {
$(this).closest('div').children('select').toggle();
});
});
//]]>
</script>
<?php
#mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
$query = "select id,language,code from language WHERE first=1";
$results = mysql_query( $query);
$lang = array();
while ($rows = mysql_fetch_assoc(#$results)){
$lang[$rows['language']] = $rows['code'];
}
?>
<form action="" method="post" name="myForm" id="myForm" >
<?php
foreach($lang as $key=>$value){ ?>
<div>
<label for="lang_<?=$value;?>" >
<input name="language[<?=$value;?>]" id="lang_<?=$value;?>" value="1" type="checkbox">
<?=$key;?>
</label>
<select style="display: none;" name="level[<?=$value;?>]" id="f_level_<?=$value;?>">
<option selected="selected" value="">your level</option>
<option value="Low">Low</option>
<option value="Average">Average</option>
<option value="Fluent">Fluent</option>
<option value="Native">Native</option>
</select>
</div>
<?php } ?>
<input value="submit" name="submit" type="submit">
<!--**********************************************************-->
<br />
<br />
<br />
<script type="text/javascript">
function showCD(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("newone").innerHTML=xmlhttp.responseText;
$('#newone').append(xmlhttp.responseText);
// document.getElementById('newone').appendChild(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "123.php?q=" + str, true);
xmlhttp.send();
}
</script>
<?php
#mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
$query = "select id,language,code from language WHERE first=0";
$results = mysql_query( $query);
$lang = array();
while ($rows = mysql_fetch_assoc(#$results)){
$lang[$rows['language']] = $rows['code'];
}
?>
<select name="level[]" id="f_level" onchange="showCD(this.value)">
<option selected="selected" value="">language</option>
<?php
$results = mysql_query( $query);
while ($rows = mysql_fetch_assoc(#$results)){
?>
<option value="<?php echo $rows['id'];?>" ><?php echo $rows['language'];?></option>
<?php
}
?>
</select>
<div id="newone"></div>
</form>
---------------
<?php
mysql_select_db('badoo',mysql_connect('localhost', 'root', ''));
if($_REQUEST)
{
$id = $_REQUEST['q'];
$query = "select id,language,code from language where id = ".$id;
$results = mysql_query( $query);
$rows = mysql_fetch_assoc($results );
if($rows!='')
{?>
<div>
<label for="lang_<?=$rows['code'];?>" >
<input name="language[<?=$rows['code'];?>]" id="lang_<?=$rows['code'];?>" value="1" type="checkbox">
<?=$rows['language'];?>
</label>
<select style="display: none;" name="level[<?=$rows['code'];?>]" id="f_level_<?=$rows['code'];?>">
<option selected="selected" value="">your level</option>
<option value="Low">Low</option>
<option value="Average">Average</option>
<option value="Fluent">Fluent</option>
<option value="Native">Native</option>
</select>
</div>
<?php
}
return;
}
?>
Unfortunately I can't yet comment everywhere so apologies for adding an answer when a comment would have sufficed.
2 suggestions for you:
1) You are using jQuery but not making use of its excellent AJAX functions. Take a look at them.
2) You are suppressing PHP warnings and errors that may be helpful to you debugging this yourself. Remove the # from the front of several of these function calls and run it again. Maybe you will see the problem yourself.
The only other thing that jumped out at me while scanning this code (since I have no idea what your problem is) is that the derived responce does not include the 'onchange' event that all of your other selects do. Is it a simple oversight?

Categories