I have a database table named tblCityState with the following data:
CITY New York,Los Angeles,Atlanta
STATE New York,California,Georgia
I have a dropdown (ddCity) bound to the table (Select City from tblCityState).
When the user Selects "Los Angeles" from the DropDown, I want a textbox (tbState) to be populated with "California".
Now, I could set the value of the DropDown Item to be the State, but I want the Item value to be the City.
What is the best / easiest way to achive this../this is so much important for me..Please help me with some code.I searched everywhere but not get anything like that.I am new in php& ajax.suggest me some code.
index.php
<script src="jquery.min.js" type="text/javascript"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#customer").autocomplete("state.php", {
width: 160,
autoFill: true,
selectFirst: false
});
$("#customer").blur(function() {
$("#customer1").val('');
$(".ac_results").next().css('height','0px');
var vState = $("#customer").val();
$("#customer1").autocomplete("city.php?state="+vState, {
width: 160,
autoFill: false,
data:{},
length:0,
});
});
});
</script>
<form name="thisForm1" method="post" id="thisForm1" action="" >
<table cellpadding="5" cellspacing="5" width="50%" align="center" class="ac_results">
<tr><td>
Enter state<input name="customer" type="text" id="customer" value="" style="width:300px;" autocomplete="off" >
</td><td>
Enter Keyword<input name="customer1" type="text" id="customer1" value="" style="width:500px;" autocomplete="off" >
</td></tr>
</table>
</form>
state.php
<?php
$db = mysql_pconnect('localhost','root','');
mysql_select_db('test',$db);
$q = strtolower($_GET["q"]);
$a = mysql_query("SELECT * FROM state");
while($b = mysql_fetch_object($a))
{
echo "$b->name\n";
}
?>
city.php
<?php
$db = mysql_pconnect('localhost','root','');
mysql_select_db('test',$db);
$q = strtolower($_GET["q"]);
$vState = $_REQUEST['state'];
if (!empty($vState)) {
$a = mysql_query("SELECT * FROM best_hotel WHERE class = '$vState'");
while($b = mysql_fetch_object($a)) {
echo "$b->name\n";
}
}
?>
Related
I have the following text fields:
<input type="text" name="empid" id="empid" tabindex="1" onblur="getname()">
<input type="text" name="name" id="name" tabindex="2"/>
<input type="text" name="city" id="name" tabindex="3"/>
<input type="text" name="state" id="name" tabindex="4"/>
and database table is:
empid name city state
EMP471 BBB bbbbb cccccc
EMP444 AAA xxxx yyyyyy
I'm new to php. I found some code on internet to retrieve data. but its not working.
Ajax code is:
function getname() {
var id=$("#id").val();
$.ajax({
type:"post",
dataType:"text",
data:"id="+id,
url:"getinsdata.php",
success:function(response)
{
$("#name").val(response.name);
$("#city").val(response.city);
$("#state").val(response.state);
}
});
}
and php code is
<?php
include 'connection.php';
$id=$_POST['id'];
$id=$_POST['id'];
$query=mysql_query("select name,city,state from ins_master where id=$id");
$result=mysql_fetch_row($query);
echo $result[0];
exit;
?>
when we select the empid then the respective name, city, state should be shown in textboxes when onblur event fires in PHP using AJAX.
What are you trying to achieve? Send the datas and get the response according to a query? Get some datas?
I'd go
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
</head>
<body>
<form id="test" method="POST">
<input type="text" id="name" required minlength="5" name="name"/>
<input type="password" id="pw" required name="pw"/>
<input id ="sub" type="submit"/>
</form>
<div id="answer"></div>
</body>
<script>
$("#sub").click(function(event){
event.preventDefault();
query = $.post({
url : 'check_ajax.php',
data : {'name': $('input[name=name]').val(), 'pw': $('#pw').val()},
});
query.done(function(response){
$('#answer').html(response);
});
});
</script>
This is check_ajax.php :
<?php
var_dump($_POST);
?>
in the second file but that's where you're supposed to do your query and insert/select
As people said we don't write code but give clues and since it's basics/fundamentals I can't help more cause you have to understand. Copy paste ain't a great idea
Try this html
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
function getname(val) {
$.ajax({
url: 'getinsdata.php',
type: 'POST',
data: 'state_id='+val,
dataType: 'json',
success:function(data){
var len = data.length;
if(len > 0){
var id = data[0]['id'];
var name = data[0]['name'];
var city = data[0]['city'];
var state = data[0]['state'];
document.getElementById('name').value = name;
document.getElementById('city').value = city;
document.getElementById('state').value = state;
}
}
});
}
</script>
</head>
<body>
<form method="post">
<input type="text" name="empid" id="empid" tabindex="1" onblur="getname(this.value);">
<input type="text" name="name" id="name" tabindex="2"/>
<input type="text" name="city" id="city" tabindex="3"/>
<input type="text" name="state" id="state" tabindex="4"/>
</form>
</body>
</html>
and getinsdata.php is
<?php
include('connection.php');
$id = $_POST['state_id'];
$sql = "SELECT * FROM ins_master WHERE id='$id'";
$result = mysqli_query($conn,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$id = $row['id'];
$name = $row['name'];
$city = $row['city'];
$state = $row['state'];
$users_arr[] = array("id" => $id, "name" => $name, "city" => $city, "state" => $state);
}
// encoding array to json format
echo json_encode($users_arr);
exit;
?>
And your connection.php
<?php
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect("localhost",$username,$password,$dbname);
if(!$conn){
die("Error in Connecation");
}
?>
put $dbname= your database name
I have a table with one column which has the list of values .The list is same in all the rows.
Now when user selects the value for first row, I want to disable it for all the rows, and when user select second value in second row, that value should be disabled in all upcoming rows and so on.So that user don't have the option to choose one value for more than one column.
I could disable the first selected value in all the columns but dont know how to do it for all the rows.
DB Table
sqlite> select * from outdoor_games;
games
----------
Badminton
Football
Basketball
Golf
Code
<?php
$db = new PDO("sqlite:c:/sqlite/games.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query_game = $db->prepare("select distinct games as di from outdoor_games;");
$query_game->execute();
$data = $query_game->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<TABLE id="STable" width="350px" border="1">
<tr> <th bgcolor="WHITESMOKE">Game Id </th> </tr>
<TR> <td><select name= "Game_id[]" class='Game'/> <option value="">Games</option>
<?php foreach ($data as $row){echo '<option value="' . $row['di'] . '">' . $row ['di'] . '</option>';} ?>
</select></td>
</TR>
</TABLE></br>
<label>No. of games <input type= "text" id="s_cnt" name= "d_Count"></label>
<button type="button" class='loadgames' >Load Games</button>
<input type="submit" name ="add_SP" value ="Add Student Info" style="float: right;" /> </br> </br>
<input type="submit" name ="exit" value ="EXIT" />
</form>
<script>
$('.Game').on('click', function()
{
var selected = $(this).val();
$('.Game').not(this).find('option[value="'+selected+'"]').prop('disabled', true);
});
$(".loadgames").on('click',function()
{
var num = $("#s_cnt").val();
$("#STable tr").slice(2).remove();
for (var i = 2; i <= num; i++)
{
var data = "<tr><td><select name='Game_id[]' class='Game'><option value='null'>Games</option><?php foreach ($data as $row){echo "<option value=".$row['di'] . ">" .$row['di']. "</option>";}?></select></td></tr>";
$("#STable").append(data);
}
});
</script>
</body>
</html>
try this:
$('select').on('change',function(){
var val = $(this).val();
var selected = $(this);
$('select').nextAll('select').find('option').each(function(){
if($(this).attr('value')==val) {
$(this).attr('disabled','disabled');
}
})
});
see the demo.
You can try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('change', '.Game', function() {
$('.Game option').removeClass("active");
$(this).addClass("active");
});
});
<script>
// For class
.Game option.active {opacity: 0.3;cursor: pointer}
I have here my Javascript code that adds dynamic textbox (row) my problem is how can I save the values from the dynamic textbox to database using PHP script? Hope you can help me guys.. Thanks!
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
My HTML code:
<form method="POST" action="#"> <table width="1024" border="0" cellspacing="6" cellpadding="0"> <tr>
<td width="195"><div class="user"><input type="text" name="user_a" id="user" tabindex="6"/></div></td>
<td width="410"><div class="reported"><input type="text" name="user_b" id="reported" tabindex="7"/></div></td>
<td width="399"><div class="reported"><input type="text" name="user_c" id="reported" tabindex="8"/></div></td>
<td width="10"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td> </tr> </table> </form>
You have to use just name of the text box which is added by dynamically.
$('form').submit(function() {
var data=($(this).serialize());
return false;
});
This function get all the elements value and create one string which is store in data, now data will pass in ajax call.
$('form').submit(function() {
var data=($(this).serialize());
$.ajax({
type: "POST",
url: "your_some.php",
data: data,
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
<html>
<head>
<title>Dynamic Form</title>
<script language="javascript">
<?php $i = 1; ?>
function changeIt()
{
//alert(i);
//var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext[<?php echo $i;?>]'><input type='text' name='mytext[<?php echo $i+1;?>]'><input type='text' name='mytext[<?php echo $i+2;?>]'><br>";
<?php $i = $i+3; ?>
}
</script>
</head>
<body>
<form name="form" action="http://localhost/try.php" method="post">
<!--<input type="text" name=t1>-->
<input type="button" value="test" onClick="changeIt()">
<div id="my_div"></div>
<p class="submit"><button type="submit">Register</button></p>
</body>
try.php(this is the file where you will be catching values and then inserting into sql
)
<?php
$var = $_POST['mytext'];
echo $var[1].$var[2];
?>
I am using Json to retrieve elements from mysql and insert them into form boxes. Displaying in form boxes(text type) was not a problem but in my html one of my form structure is dropbox ... How should i display info that is in the database to the one that is in dropbox??
Here is the code that i used for displaying elements in form type (text). One of them is dropbox in the html.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='rno']").val(json.rno);
$("input[name='url']").val(json.url);
}, "json");
});
</script>
</head>
<body>
<form id="myForm" method="post">
id: <input type="text" name="id"/>
<input type="button" id="button1" value ="Get"/>
<input type="button" id="button2" value="Submit to script 2" />
<p>title:<input type="text" name="title"/></p>
<p>Report No:<input type="text" name="rno"/></p>
<p>URL:<input type="text" name="url"/></p>
Institution: <select name="institution">
<option value="abc">abc</option>
<option value="cdf">cdf</option>
</select>
</form>
<div id="age"></div>
</body>
</html>
PHP part or script_1.php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
//connect to DB part
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
**//i am not using $row['institution'] (no institution or dropbox part)**
$abc_output = array('title' => $row['title'],'rno' => $row['reportno'],'url' => $row['calc_url']);
}
}
echo json_encode($abc_output);
}
}
?>
Help appreciated.John.
var option1 = new Option("InstitutionName1","InsitutionValue1");
var option2 = new Option("InstitutionName2","InsitutionValue2");
document.myForm.institution.options.length = 0;
document.myForm.institution.options[0] = option0;
document.myForm.institution.options[1] = option1;
This is the way its done normally. In this particular case, you may want to have a for loop or something or jQuery's each(..).
#John
You can put the following snnipet of code at the end of the script tag:
for (item in json.institution) {
$('select[name="institution"]').html('').append('<option value="' + json.institution[item].value + '">' + json.institution[item].text + '</option>');
}
where:
json.institution is a named array that will be returned along with the other form fields by your .php script.
json.institution[item].value is the value of each option.
json.institution[item].text is the text of each option.
The .html('') code is for clear the previous loaded select options.
I am trying to update the database using jquery and ajax. A pop up window is opened for updating the fields. My problem is : the database is udapted fine but the values are not reflected on the web page without refreshing the page. I am using jquery .html() method to update the contents.
Please help me with the problem.
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript' src="js/jquery-1.5.1.min.js"></script>
<script type='text/javascript' src="js/jquery-ui-1.8.13.custom.min.js"></script>
<link rel='stylesheet' href="js/jquery-ui-1.8.13.custom.css" />
<script type='text/javascript'>
$(document).ready(function() {
$update_dialog = $("#update_dialog").dialog({
autoOpen:false,
title:"Update Sub Sub Section",
width: '600px',
modal:true,
buttons:[
{text: "Submit", click: function() { $('form',$(this)).submit(); }},
{text: "Cancel", click: function() { $(this).dialog("close"); }},
]
});
$("#update_dialog form").submit(function() {
var form = $(this);
alert($(this).serialize());
$.post($(this).attr('action'), $(this).serialize(),function(data) {
var getbook = $('#book_'+data.id);
$('.description',getbook).empty().html(data.description);
$("#update_dialog").dialog('close');
},'json');
return false;
});
function edit3_link_action() {
var getbook = $(this).closest('.book');
//get id from div
var id = getbook.attr('id').split('_');
id = id[id.length-1];
$('#update_dialog input[name="id"]').val(id);
$('#update_dialog textarea[name="description"]').val($('.description',getbook).html());
$update_dialog.dialog('open');
return false;
}
$(".edit3").click(edit3_link_action);
});
</script>
</head>
<body>
<div align="center">
<form name="userform" method="post">
<?php
$proposalid='P09-001';
$res=mysql_query("Select * from tblproposaldocsections where ProposalID='$proposalid' order by SortOrder;");
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_row($res);
if($row[1]!=$row[2])
{
$result=mysql_query("Select * from tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row[1]' order by SortOrder;");
for($k=0;$k<mysql_num_rows($result);$k++)
{
$row1=mysql_fetch_row($result);
$exp=explode('.',$row1[2]);
$alter=$row[2].'.'.$exp[1].'.'.$exp[2];
$result1=mysql_query("Select * from tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row1[2]' order by OrderID;");
$lastsortorder= mysql_query("SELECT Max(SortOrder) FROM tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row1[1]';")or die(mysql_error());
$rr = mysql_fetch_row($lastsortorder);
$lastsortorder = $rr[0];
if(mysql_num_rows($result1)>0)
{
?>
<br>
<?php
for($j=0;$j<mysql_num_rows($result1);$j++)
{
$row2=mysql_fetch_row($result1);
$exp=explode('.',$row2[2]);
$alter=$row[2].'.'.$exp[1].'.'.$exp[2].'.'.$exp[3];
$lastsortorder= mysql_query("SELECT Max(SortOrder) FROM tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row2[1]';")or die(mysql_error());
$rr = mysql_fetch_row($lastsortorder);
$lastsortorder = $rr[0];
?>
<div class='book' id='book_<?php echo $row2[2];?>'>
<h3 class="title"><?php echo $alter;?> subsubsection_<?php echo $row2[2];?></h3>
<p class='description'><?php echo $row2[3];?></p>
<a class="edit3" href="#">Edit</a>
</div>
<br>
<?php
}
?>
<br>
<?php
}
}
}
echo('<br>');
}
?>
</table>
</form>
</div>
<div id='update_dialog'>
<form action='edit.php' method='post'>
<table>
<tr>
<td align="left">Description:</td>
<td>
<textarea name='description' cols='60' rows='5'></textarea>
</td>
</tr>
</table>
<input type='hidden' name='id' />
<input type='hidden' name='proposalid' value="<?php echo $proposalid;?>" />
</form>
</div>
</body>
</html>
EDIT by blasteralfred
I used FireBug for debugging and the problem was the same as expected. DOM object is unable to read updated data. Is this declaration for getting the DOM element correct? This is the only problem !
var getbook = $('#book_'+data.id);
This is how the tag is declared:
<div class='book' id='book_<?php echo $row2[2];?>'>
<table width="80%" align="left">
<tr>
<td width="10%"><?php echo $alter;?></td>
<td width="70%" class="description"><?php echo $row2[3];?></td>
<td width="10%" align="center"><a class="edit" href="#">Edit</a></td>
</tr>
</table>
</div>
If your .html() isn't working, its either because the element you're using it on isn't there or the value you're trying to set isn't defined.
You can figure out what's up by checking if the given element and the value are defined prior to the .html() call. I'd recommend FireBug for debugging, but this can also be done simply by alert()ing the element and the value..