I understand this question may be entirely juvenile however I have been trying to debug it for an entire afternoon, not using an IDE other than sublime. would be really glad to receive any help and format this question nicely for future begineers when it works.
currently
my html.
<?php
//connect to the server & database
$connect = mysqli_connect('localhost','root','root','ikea');
if(!$connect)
{
echo "failed to connect ".mysqli_connect_error();
}
// query the database
$query = 'SELECT * from department
where iconpath Like "image%"
order by name asc';
$result = mysqli_query($connect,$query);
// retrieve the resultset
while( $row[] = $result->fetch_object());
?>
<form id="question2" method="POST">
<div class="form-group input-group">
<select style="width:8.7cm;" id="member_choice" class="form-control">
<option value="">-- Select One --</option>
<?php foreach($row as $option) : ?>
<option value="<?php echo $option->name; ?>"><?php echo $option->name; ?></option>
<?php endforeach; ?>
</select><br/><br/>
<button id="q2-submit" name="q2-submit" style="margin-left:5cm;" type="submit" class="btn btn-default btn-add"> Get Departments! </button>
</div>
</form>
my jquery
$('#question2').on('submit', function()
{
alert("submit!");
// AJAX STUFF HERE
$.post('q3.php', function(data)
{
console.log("here1");
$(".return").html(data);
});
});
and currently experimenting with my php trying to get it to return "content"
<?php
echo "content";
?>
Your question keeps changing. Honestly, I recommend you go through a tutorial on how to submit a form using AJAX with jQuery, like this one.
You should use submit handler instead of a click handler. Also your selector is wrong.
HTML
added name attribute to the <select> tag.
<form id="question2" method="POST" action="q2.php">
<div class="form-group input-group">
<label>Select Member Card Number</label>
<select name="member_choice" style="width:8.7cm;" id="member_choice" class="form-control">
<option value="">-- Select One --</option>
<?php foreach($row as $option) : ?>
<option value="<?php echo $option->name; ?>"><?php echo $option->name; ?></option>
<?php endforeach; ?>
</select><br/><br/>
<button style="margin-left:5cm;" type="submit" class="btn btn-default btn-add"> Get Departments! </button>
</div>
</form>
<div id="content"></div>
JQUERY
$('#question2').on('submit', function(event)
{
// stop form from submitting normally
event.preventDefault();
var $form = $(this);
var url = $form.attr('action');
$.post(url, $form.serialize(), function(data)
{
console.log("here1");
$('#content').html(data.content);
});
});
PHP (q2.php)
<?php
$content = $_POST['member_choice'];
echo json_encode($content);
?>
Your click handler doesn't prevent the form from submitting (the page gets refreshed) so you never see the ajax response. Use a submit handler instead:
$('#question2').on('submit',function(e)
{
var name = $('#department_choice :selected').val();
console.log("here");
$(".return").html("asdad");
$.post('q2.php', function(data)
{
console.log("here1");
$(".return").html(data);
});
return false;//prevent form submit
});
Related
When I select one of the year from drop-down list so, how to show the title that related to year into input fields of the form below.
$formationSQL = "SELECT title FROM formationacademique";
$result = $connection->query($formationSQL);
<form method="post">
<label>Select year:</label>
<select>
<?php foreach($result as $formation): ?>
<option id="formationID" name="formationID" value="<?= $formation['ID_Formation']; ?>"><?= $formation['year']; ?></option>
<?php endforeach; ?>
</select>
<label>title:</label>
<input type="text value="">
</form>
Here are some changes that are needed for your html formatting. Would need to know if you are wanting this change to happen with javascript or in php? If you don't know the difference, it is that php is server side that will only parse on page load and javascript can do it without a page refresh or reload.
$formationSQL = "SELECT title FROM formationacademique";
$result = $connection->query($formationSQL);
<form method="post">
<label for="formationID">Select year:</label>
<select id="formationID" name="formationID">
<?php foreach($result as $formation): ?>
<option value="<?php $formation['ID_Formation']; ?>"><?= $formation['year']; ?></option>
<?php endforeach; ?>
</select>
<label for="input_title">title:</label>
<input type="text" id="input_title" name="input_title" value="<?php $formation['ID_Formation']; ?>">
</form>
Add the following script contents to your js file or add the script after the form above for the javascript verse of changing the inputs value.
<script>
var year_select = document.getElementById( 'formationID' );
var year_title = document.getElementById( 'input_title' );
year_select.addEventListener( 'change', function( e ) {
year_title.value = year_select.selectedIndex.value;
});
</script>
How do I create a dynamic select input with options from PHP whenever I click on a button?
The working should go like this:
Whenever I click on a button, a select element with options from PHP should be available to choose from.
<div class="form-group">
<label class="control-label col-sm-2" for="product">Products:</label>
<div class="col-sm-4">
<select class="form-control" name="product[]" multiple required>
<option selected="selected">--SELECT PRODUCT--</option>
<?php
$sql = "SELECT * FROM `product`";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
?>
<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>
</div>
</div>
Whenever I click on a button, I should be able to create a new select input with the above-mentioned code.
here you need to use ajax like below
function getOptions(query){
$.post(endPoint, query, function(response){
$('select[name="product[]"]').empty();
response.forEach(function(value){
$('select[name="product[]"]').append("<option value='" +value+ "'></option>");
});
})
}
and trigger it on click
$('body').on('click', '#myButton', function(){
getOptions(null);
});
I am using Jquery and PHP. So that on selection of first dropdown the value of first drop down should be passed to a Mysql query and then populate the second dropdown, but the second drop down displays blank.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#city").change(function() {
var value = $(this).val();
$.ajax({
type : "GET",
url : 'abc.php',
data : {
choice : value
},
success : function(data){
$('#123').html(data);
}
})
});
});
</script>
<form action="" method="post">
<select class="form-control" id="city" action="" name="city" value="">
<option value="">--</option>
<option value="1"</option>
<option value="2"</option>
<option value="3"</option>
</select>
<br/>
</div>
<div class="form-group">
<select class="form-control" action="" name="123" id="123"">
<option value="--">--</option>
<?php
$query = "SELECT DISTINCT `Comm` FROM `Comm_New` WHERE `Market`='".$_GET['city']."' ORDER BY `Comm` ASC";
if ($result = mysqli_query($link, $query)) {
while ($Comm = mysqli_fetch_assoc($result)) {
print_r("<option value='".$Comm['Comm']."'>".$Comm['Comm']."</option>");
}
}
?>
</select><br/>
</div>
From our conversation in the comments you are calling the same page that you are originally loading. That is not necessarily a problem technically, it's just not implemented properly. To load the same page, you need to do:
<?php
// Make sure your database is initiated above here so this can use it.
// I am going to demonstrate a basic binding using a super basic PDO
// connection because procedural mysqli_* with bind is just annoying
$link = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Notice that you send "choice" as the GET key in your ajax, not "city"
if(!empty($_GET['choice'])) {
?>
<select class="form-control" action="" name="123" id="123"">
<option value="">--</option>
<?php
// prepare, bind, execute here
$query = $link->prepare("SELECT DISTINCT `Comm` FROM `Comm_New` WHERE `Market` = :0 ORDER BY `Comm` ASC");
$query->execute(array(':0'=>$_GET['choice']));
// PDO has a lot of connection settings where you can set the default
// return type so you don't need to tell it to fetch assoc here.
// Also, you would tell the the connection not to just emulate bind
// etc.. I would consider using PDO or the OOP version of mysqli
while ($Comm = $query->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='".$Comm['Comm']."'>".$Comm['Comm']."</option>";
}
?> </select>
<?php
// Stop the page from running further
die();
}
?><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#city").change(function() {
var value = $(this).val();
$.ajax({
type : "GET",
url : 'abc.php',
data : {
choice : value
},
success : function(data){
// Populate the empty container #new_drop
$('#new_drop').html(data);
}
})
});
});
</script>
<form action="" method="post">
<select class="form-control" id="city" action="" name="city" value="">
<!--
Your options are malformed. Missing close ">"
probably just copy error
-->
<option value="">--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br/>
</div>
<!-- Add id="new_drop" to this div -->
<div class="form-group" id="new_drop">
</div>
Ideally you want to have the top part on a new page, and possibly return a set of data as opposed to straight html, but ajax is very flexible.
in a web form there are two drop-down lists. The second list items should change dynamically depending on the value selected on the first drop-down list.
This is how am I trying to do it:
index.php:
...
<script>
function getClient(val) {
$.ajax({
type: "POST",
url: "get_contacts.php",
data:'client_id='+val,
success: function(data){
$("#contacts-list").html(data);
}
});
}
</script>
...
<div class="form-group">
<label for="mto_client" class="col-sm-2 control-label">MTO Client</label>
<div class="col-sm-10">
<select name="mto_client" id="clients_list" onChange="getClient(this.value)">
<option value="">Select a Client</option>
<?php
do {
?>
<option value="<?php echo $row_RSClients['id_client']?>" ><?php echo $row_RSClients['client_name']?></option>
<?php
} while ($row_RSClients = mysql_fetch_assoc($RSClients));
?>
</select>
</div>
</div>
<div class="form-group">
<label for="mto_client_contact" class="col-sm-2 control-label">MTO Client Contact</label>
<div class="col-sm-10">
<select name="state" id="contacts-list">
<option value="">Select Client Contact</option>
</select>
</div>
</div>
get_contacts.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["client_id"])) {
$query ="SELECT * FROM tb_client_contacts WHERE contact_client_id = '" . $_POST["client_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select Client Contact</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id_client_contact"]; ?>"><?php echo $state["contact_name"]; ?></option>
<?php
}
}
?>
There are objects on the table tb_clients_contact that meet the condition, but the second drop-down list doesn't show any objects.
Any help is welcome.
Instead of
$("#contacts-list").html(data);
It should be
$('#contacts-list').empty().append(data);
empty() will clear first the options inside the contacts-list select field, then append() will insert the options from the result of your AJAX.
You can also look at the console log for errors. If you are using Google Chrome, hit F12 to display the console log.
I have this code :
<form id="frmKat" role="form" action="" method="post">
Country :
<select name="country" id="country">
<option>-select your country-</option>
<?php
$result=mysqli_query($kon, "SELECT * from regios");
while($country=mysqli_fetch_assoc($result)){
echo "<option value=$country[id]>$country[naam]</option>";
} ?>
</select>
City :
<select name="city" id="city">
<option>-select your city-</option>
</select>
<div style="clear:both;"></div>
<button type="submit" class="pull-right btn btn-success" name="btnConvert" id="btnConvert">Convert</button>
</form>
My ajax code is :
<script type="text/javascript">
$(document).ready(function(){
$("#country").change(function(){
var country=$("#country").val();
$.ajax({
type:"post",
url:"getcutoff.php",
data:"country="+country,
success:function(data){
$("#city").html(data);
}
});
});
});
</script>
And my getcutoff.php file is next :
<?php
session_start();
include("config.php");
global $kon;
ob_start();
if(isset($_SESSION["admin"])){
$country=$_POST["country"];
$result=mysqli_query($kon, "select * FROM cutoffs WHERE regio_id=". $country ." ");
while($city=mysqli_fetch_array($result)){
echo "<option value=$city[id]>$city[datetime]</option>";
}
}else{
ob_flush();
die("Salut");
}
?>
I'm trying to make dependable selectboxes. When user chooses something in the first selected box, then they will be taken to the second one where they can choose values which are connected to the first selected box. In first box I get values, but when I choose something in the second one, I get nothing. Where am I making a mistake?
Group your options in a php variable as string and use a single echo in getcutoff.php
$res ='';
while($city=mysqli_fetch_array($result)){ $res.="<option value=$city[id]>$city[datetime]</option>"; }
echo $res;
your echo looks a bit wrong. Also, I assume you have saved your daetime as DateTime in SQL, thus you'd need to convert it before defining it as a string.
$date = strtotime($city[datetime]);
$date = date('Y-m-d H:i:s', $date);
echo "<option value='".$city[id].">".$date."'>My Option</option>";