I have the below code and I'm stuck finding solution for my problem. I want to select a value from a dropdown menu according on what the PHP result is.
<form>
<select name="filter" id="filter">
<option value="">Select</option>
<option value="AT_001">AT_001</option>
<option value="GG_001">GG_001</option>
</select><br><br>
<input type="text" name="name" id="name"><br><br>
<input type="text" name="reference" id="reference"><br><br>
<select name="gender" id="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</form>
$("#filter").change(function () {
var id = $(this).val();
$.ajax({
url : "getdata.php",
data : {
"id" : id
},
type : "POST",
dataType : "json",
success : function(data) {
console.log(data);
$("#name").val(data.fname);
$("#reference").val(data.reference);
$("#gender").attr("", data.gender); // ????? <--
}
});
});
$id = $_POST['id'];
$query = "SELECT fname, reference FROM tb_amity WHERE coc = '$id'";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
echo json_encode($row);
}
You can use val() to set the selected option of a select element:
$("#gender").val(data.gender);
This is assuming that the data.gender value returned by your PHP is either 'Male' or 'Female'
First console what you are getting inside 'data.gender', if its value is present inside your options value then it works fine like:
$("#gender").val(data.gender);
Related
I can't seem to save all the clone inputs into an array and pass the array via $.post(). For some reason it only passes the first array value that user selects.
I would like to
pass array by $.Post()
receive true or false if all items in array don't exist in mysql via a php.
I am stuck on the array only holding the value of the original input.
$(document).ready(function() {
$("#add").click(function() {
$("p:last").after($("p:first").clone(true)
.find("#Equi").val("").end()
);
});
});
$(document).ready(function() {
var ar1 = [];
var input = document.getElementById('#Equi');
$('#Equi').on('change', function() {
// $.post('UnitValidate2.php', {Unit: ar1}, function(data) {
ar1.push(input.value);
window.alert(ar1);
$.post('UnitValidate2.php', {Unit: ar1}, function(data) {
window.alert(data);
if(data == "True") {
window.alert("Move On");
} else {
window.alert("Cant call out unit");
// $("#Equi").val("");
}
});
});
});
<!--for clone -->
<p>
<label for="lname">Eqiupment:</label>
<!--<input type="text" id="Name" name="Name">-->
<input type="text" name="Unit[]" id="Equi" value="" list="namelist4" required/>
<datalist id="namelist4">
<select name="Nam" style="display:none">
<?php
// Include config file
require_once "../Login/config.php";
$conn1 = mysqli_connect($serverName, $userName, $password, $databaseName);
$sql4 = "SELECT * FROM `Status` WHERE Active = 'Yes' AND Status = 'Ready For Rent' ORDER BY Unit ASC";
result4 = mysqli_query($conn1,$sql4);
while ($row4 = mysqli_fetch_array($result4)) {
echo "<option value='".$row4['Unit']."'>".$row4['Unit']."</option>";
}
?>
</option>
</select>
</datalist>
There is still a lot unclear to me. I left out the PHP part where you fill the options in the <select> element. I also made up some elements for your <datalist> element. And ...
Since you are using jQuery you might as well use it properly: I changed your data collecting part to
var ar1=$('.Equi').get().map(el=>el.value);
where I search for all elements of class=Equi (I had to change this from id to class, since Ids must always be unique!), then extract them as a JavaScript Array (.get()), use .map() to get their .value attribute and eventually return the resulting array into ar1.
Since this snippet runs on Stackoverflow I had to comment out the actual $.post() commands but the console.log() shows what would have been posted in it.
$(document).ready(function() {
$("#add").click(function() {
$("p:last").after($("p:first").clone(true).find(".Equi").val("").end() );
});
$('.Equi').on('change', function(){
var ar1=$('.Equi').get().map(el=>el.value);
console.log("this will be posted:",ar1);
if (false) $.post('UnitValidate2.php',{Unit: ar1}, function(data){
console.log(data);
if(data == "True"){ console.log("Move On ");}
else { console.log("Cant call out unit");}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">add</button><br>
<datalist id="namelist4">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</datalist>
<p>
<label for="lname">Eqiupment
<input type="text" name="Unit[]" class="Equi" value="" list="namelist4" required/>:</label>
<select name="Nam">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</p>
<p></p>
https://i.stack.imgur.com/2O2Ug.png
when i change course name first row change only that row parent topic
how to do this please give advice
first course name select box code
<select class="form-control select2" onChange="getval(this.value)"; id="course_id1" name="course_id[]" data-live-search="true" >
<option value="" selected="selected"> Select Course Name</option>
<?php
$sql = "SELECT * from course_master";
$result = $connect->query($sql);
while($row_pt = $result->fetch_array())
{
?>
<option value="<?php echo $row_pt['course_id']; ?>" ><?php echo $row_pt['course_name']; ?></option>
<?php
}
?>
</select >
second select box when i select course name from drop down change that row parent id
<select class="form-control select2" id="parent_id" name="parent_id[]" data-live-search="true" ></select>
call function on change in course name
function getval(val)
{
$.ajax({
type: "POST",
url: "get.php",
data: {parent_id:val,syllabus_id:syllabus_id},
success: function(data)
{
$("#parent_id").html(data);
}
});
}
get.php
<?php
include('connection/core.php');
if(isset($_SESSION['userId']))
{
if (!empty($_POST["parent_id"]))
{
$query_sql = "SELECT syllabus_id,topic_name FROM syllabus WHERE syllabus_id!='". $_POST["syllabus_id"]."' AND course_id ='" .$_POST["parent_id"] ."'";
$results = $connect->query($query_sql);
echo $query_sql;
?>
<option value="0" selected> Parent </option>
<?php
foreach ($results as $p)
{
?>
<option value="<?php echo $p["syllabus_id"]; ?>"><?php echo $p["topic_name"]; ?></option>
<?php
}
}
}
?>
Add below code for your first row.
For example.
<select class="form-control select2 selectCourse" data-id="1" id="course_id_1" name="course_id_1[]" data-live-search="true" >
And for your parent topic name add as below.
<select class="form-control select2" id="parent_id_1" name="parent_id_1[]" data-live-search="true"></select>
Now when you are adding new dynamic row in your HTML then add selectCourse as class name in your select box of course name AND data-id="1" for each dynamically added row.
For example.
For course name add as below.
<select class="form-control select2 selectCourse" data-id="2" id="course_id_2" name="course_id_2[]" data-live-search="true" >
For parent topic name add as below.
<select class="form-control select2" id="parent_id_2" name="parent_id_2[]" data-live-search="true"></select>
In your script add code as below.
<script type="text/javascript">
$(document).on('change', '.selectCourse', function(){
var course_id = $(this).attr('data-id');
var val = $(this).find(":selected").val();
var syllabus_id = 1;
$.ajax({
type: "POST",
url: "get.php",
data: {parent_id:val,syllabus_id:syllabus_id},
success: function(data)
{
$("#parent_id_" + course_id).html(data);
}
});
});
</script>
Problem: How can I update a form's select input values and text input fields based on a MySQL query after select input's onchange event is fired?
What I've tried:
I have tried to use AJAX with post and get data types, calling a php file that runs the query and echoes the results. Nothing displays. Any errors I have gotten along the way are usually small things that result in server 500 error. I have placed console.log statements in the function that runs the JQuery AJAX request. The change event was detected, the ajax success was called. I also tried using .load(), with GET and POST, no luck either. I have other features that implement AJAX, and I've tried modifying them to fit this scenario and have been unsuccessful.
I also tried to only use a select input that when changed would use AJAX request and .load function to display the other inputs which would be formatted on the php side and echoed to page with selected and values reflecting the db result.
What I want:
I would like a simple example of a form with a select input with three options, text type input, and a submit button. The form is a client backend form to send updates to the MySQL db. Each input represents a filed in the db. The idea is that when the user changes the select inputs selected value, a query is done that uses the selected value for only returning one result. Each field of that one records values in db should now be reflected in the form. First, tell me if this is the correct way to approach this problem, and if not show me how you would.
Example index.php:
<form action="editForm.php" method="POST" enctype="multipart/form-data">
<select id="contact_name" name="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" name="age" placeholder="Age" required>
<input type="text" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
When on change event for #contact_name is fired I need to update the fields with the values the db has.
How would you implement this? Thanks in advance.
Update: as requested here is my JQuery code, but I know my example doesn't use the same names.
<script type="text/javascript">
$(document).ready(function(){
$('#currency_select').on('change', function (e) {
$.ajax({
type: 'post',
url: 'getCurrentValues.php',
data: {currency: 'EUR'},
success: function () {
console.log('ajax was submitted');
}
});
});
});
</script>
Here is my understanding of how to do this:
First, detect event and pass data via ajax for the query to retrieve record. This is in the document ready function to ensure DOM is ready.
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function () {
console.log('ajax was submitted');
}
});
};
editForm.php:
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
$age = $row['age'];
}
<input type="text" name="age" value="<?php echo $age; ?>">
<?php
}
?>
your index:
<select id="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<form action="editForm.php" id="form" method="POST" enctype="multipart/form-data">
<select name="contact_name" id="contact_form" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" id="age" name="age" placeholder="Age" required>
<input type="text" id="race" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
$("#contact_name").on("change", function() {
var selected = $(this).val();
$("#form").load("formdata.php?contact="+selected); //normaly you do that with an id as value
OR
$.ajax({
type:"POST",
url:"formdata.php",
data: {user: selected},
dataType: "json",
success: function(response){
if(response.status == "success") {
$("#age").val(response.age);
$("#race").val(response.race);
$("#veteran_status").val(response.status);
} else {
alert("No data found for this user!");
}
});
});
and in your formdata.php file
//make your db-query
then either make the actual input fields which will be displayed if you use load
OR make something like if you use the ajax version
if($result) {
echo json_encode(array("status" => "success",age" => $result["age"], "race" => $result["race"], "status" => $result["status"]));
} else {
echo json_encode(array("status" => "failed"));
}
also you can delete the action, method and enctype in your form, as this will be set in the ajax function ;)
I would advice you to use the userid as the value in your select field, and you will also need to either also fill the contact_name IN the form OR make an hidden input field so that you can submit the form and know whos data this is..
just echo the $age variable in your editForm.php file and in the AJAX call success function alert the response. like so-
editForm.php
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
echo $age = $row['age'];
}
}
?>
Ajax file
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function (response) {
alert(response);
console.log(response);
}
});
};
I have a form that i would like to submit details when an option is selected from the database.
The mysql database table :-
USERS contains fields like [email],[age],[name].
I want to be able to populate the other input fields values when one field is selected from the menu.
<form>
User
<select name="user" id="user">
<option>-- Select User --</option>
<option value="Mark">Mark</option>
<option value="Paul">Paul</option>
<option value="Hannah">Hannah</option>
</select>
<p>
Age
<input type="text" name="age" id="age">
</p>
<p>
Email
<input type="text" name="email" id="email">
</p>
</form>
How do i acheive this using jquery or javascript.
Please Try this,
on your HTML page:
write this to your html page,
<script>
$(document).ready(function(){
$('#user').on('change',function(){
var user = $(this).val();
$.ajax({
url : "getUser.php",
dataType: 'json',
type: 'POST',
async : false,
data : { user : user},
success : function(data) {
userData = json.parse(data);
$('#age').val(userData.age);
$('#email').val(userData.email);
}
});
});
});
</script>
in getUser.php:
getUser.php
<?php
$link = mysqli_connect("localhost", "user", "pass","mydb");
$user = $_REQUEST['user'];
$sql = mysqli_query($link, "SELECT age,email FROM userstable WHERE name = '".$user."' ");
$row = mysqli_fetch_array($sql);
json_encode($row);die;
I am trying to create a dependent dynamic drop down box on three input fields. At the moment the each input field is getting their data from their individual tables called tour_type, countries and destination. This is the form:
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required>
<option value="" selected="selected">-- Select --</option>
<?php
$sql=mysql_query("SELECT * FROM `countries` where `tour_type_id` = ?"); //what should i put in here?
while($row=mysql_fetch_array($sql))
{
$cid=$row['countries_id'];
$name=$row['countries_name'];
echo "<option value='$cid'>".$name."</option>";
}
?>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
<?php
$sql=mysql_query("SELECT * FROM `destination` where `countries_id` = ?");//what should i put in here?
while($row=mysql_fetch_array($sql))
{
$destination_id=$row['destination_id'];
$name=$row['destination_name'];
echo "<option value='$destination_id'>".$name."</option>";
}
?>
</select>
This is the javascript at the top of the form
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$(".destination").html(html);
}
});
});
});
</script>
Finally these are the 3 tables i.e. tour_type, countries and destination respectively:
Can anyone help me on this?
How do I make each drop down box dependable on each other? For e.g. If i select Culture on the 1st drop down, then only Holland and Belgium should show in the 2nd drop down. So now if i select Holland from 2nd drop down, then Amsterdam should show in the 3rd drop down.
This is the ajax.php which i am not too sure if it is right.
<?php
include('../config.php');
if($_POST['']) //what should i put in here?
{
$id=$_POST['']; //what should i put in here?
$sql=mysql_query //this is where i do not know what to put;
while($row=mysql_fetch_array($sql))
{
//And what should i be placing here
}
}
?>
This is what the web front end form looks like after implementing the code provided by dianuj. I still can not select the 2nd and 3rd drop down boxes:
So first you have the tour type select box. So just move the code for fetching countries based on tour type to ajax.php. Also include one more parameter to distinguish which type(tour type,country etc) you are posting. so you will get the id and based on the type parameter you can fetch from different tables. Then create a selectbox HTML snippet and output it. This will return for the AJAX call and you can insert the HTML.
You can use ajax get here and can use the shorthand version like
$.get('ajax,php?id=idhere&type=country', function(data) {
$('#country_result').html(data);
});
Where result is the id of div to which the select box has to be inserted.
So the HTML part will be like
<div id="country_result"></div> //Country select box goes here
<div id="destination_result"></div> //Country select box goes here
The simplest approach is to fetch select options from the server when the selections change, like so:
$('#tour_type').change(function() {
// load country options
});
$('#country').change(function() {
// load destination options
});
The server should simply return a snippet of HTML containing the available options for country and destination.
here you go you have to fetch the options from the ajax.php do not place the query in second dropdown
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" >--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required>
<option value="">-- Select --</option>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="">-- Select --</option>
</select>
initially country and destination drop down should be empty here your js goes
$('#tour_type').change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: "&id="+id+"&get_countries=1",
success: function(html)
{
$("#country").append(html);
}
});
});
$('#country').change(function() {
var id=$(this).val();
$.ajax
({
type: "POST",
url: "ajax.php",
data: "&id="+id+"&get_destination=1",
success: function(html)
{
$("#destination").append(html);
}
});
});
And your ajax.php
<?php
if($_REQUEST['get_countries']){
$sql=mysql_query("SELECT * FROM `countries` where `tour_type_id`=".$_REQUEST['id']);
$countries="";
while($row=mysql_fetch_array($sql))
{
$cid=$row['countries_id'];
$name=$row['countries_name'];
$countries.= "<option value='".$cid."'>".$name."</option>";
}
echo $countries;
}elseif($_REQUEST['get_destination']){
$destination="";
$sql=mysql_query("SELECT * FROM `destination` where `country_id` =".$_REQUEST['id'])
while($row=mysql_fetch_array($sql))
{
$destination_id=$row['destination_id'];
$name=$row['destination_name'];
$destination.= "<option value='".$destination_id."'>".$name."</option>";
}
echo $destination;
}
?>
Hope it works fine
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required onchange="get_country($(this).val())">
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country </label>
<select id="country" name="country" class="country" required onchange="get_destination($(this).val())">
<option value="" selected="selected">-- Select --</option>
</select>
<label>Destination </label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
</select>
<script>
function get_country(tour_type)
{
$.post("ajax.php",{get_country:tour_type},function(data){
var data_array = data.split(";");
var number_of_name = data_array.length-1;
var value;
var text;
var opt;
var temp_array;
for(var i=0; i<number_of_name; i++)
{
value=temp_array[i];
//alert(value);
text=temp_array[i];
opt = new Option(text,value);
$('#country').append(opt);
$(opt).text(text);
}
$("#country").prop("disabled", false);
});
}
//same way script for getting destination
</script>
// now in ajax file
if(isset($_POST["get_country"]))
{
$tour_type = str_replace("'","",stripslashes(htmlentities(strip_tags($_POST["get_country"]))));
$country_select = mysql_query("select * from country where tour_type_id = '$tour_type'");
$country="";
while($country_row = mysql_fetch_array($country_select))
{
$country = $country.$country_row["country"].";";
}
echo $country;
}
// same way ajax for destination