Pulling MYSQL (PHP) values in to JSON -> Error Undefined - javascript

I'm trying to push information from MYSQL, in a PHP File named edit_v and, in my main file "editar_v" I want to fill the input fields inside my forms so after that, user can edit the info related to the vehicle that is stored in my database. For that, I'm using Ajax, so the page doesn't get reloaded/changed.
Here is my main code of editar_v.php:
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<form method="POST" action="editar_v.php">
<div class="form-row">
<div class="form-group col-md-12">
<label for="input_veiculo_editar">Escolha o veículo que pretende editar:</label>
<select class="custom-select my-1 mr-sm-2" id="dropdown_matricula">
<option selected>Veículos Disponíveis</option>
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$sql = "SELECT id, matricula FROM veiculo";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['id']."'>".$row['matricula']."</option>";
}
}
?>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_marca">Marca do Veículo:</label>
<input type="text" class="form-control" id="input_marca" disabled value="NOTHING">
</div>
<div class="form-group col-md-6">
<label for="input_modelo">Modelo do Veículo:</label>
<input type="text" class="form-control" id="input_modelo" disabled>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_cilindrada">Cilindrada (CV):</label>
<input type="text" class="form-control" id="input_cilindrada" disabled>
</div>
<div class="form-group col-md-6">
<label for="input_potencia">Potencia do Veículo:</label>
<input type="text" class="form-control" id="input_potencia" disabled>
</div>
</div>
<div class="form-group">
<label for="input_combustivel">Combustível:</label>
<input type="text" class="form-control" id="input_combustivel" disabled>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for"input_ano">Ano do Veículo:</label>
<input type="text" class="form-control" id="input_ano" disabled>
</div>
<div class="form-group col-md-6">
<label for="input_modelo">Modelo do Veículo:</label>
<input type="text" class="form-control" id="input_modelo" disabled>
</div>
</div>
<div class="form-group">
<label for="input_escolaID">Escola de Condução a que pertence:</label>
<select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref" disabled>
<option selected></option>
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$sql = "SELECT id_escola, nome FROM escola";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['id_escola']."'>".$row['nome']."</option>";
}
}
?>
</select>
</div>
<input type="button" value="Procurar Veículo" id="procuraveiculo">
<input type="button" value="Editar Veículo" id="adicionar_veiculo">
<span id="jsonresultado"></span>
</form>
</div>
</div>
</div>
Inside the same file, i have the following javascript / jquery:
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log("Document ready!");
$("#procuraveiculo").on('click', function() {
var e = document.getElementById("dropdown_matricula");
var strUser = e.options[e.selectedIndex].text;
alert(strUser);
$.ajax({
method: "POST",
url: "admin_pages/veiculo_pages/edit_v.php",
data: {matriculaPHP:strUser},
complete: function(data) {
var yourDataStr = JSON.stringify(data);
var result = yourDataStr;
console.log(result[0].marca);
},
error : function (data) {
console.log("error:"+data.message);
console.log("DATA ERROR:: " + data.msg);
},
dataType: "JSON",
});
});
});
</script>
So in this part of the code, i give the user the option to select one of the available vehicles in the database.
After that, i send it to php file in matriculaPHP, and this is working properly.
Now, there is my edit_v.php:
<?php
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
echo "Base de dados conectada!";
}
else
{
echo "Error " . $sql . "<br>" . $conn->error;
}
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
print json_encode($data);
header('Content-type: application/json');
echo json_encode($data);
?>
Conclusion: When i execute my code, i get the right values from the database. Example: [{"marca":"Citroen","modelo":"C3","cilindrada":"1100","potencia":"60","combustivel":"Gasolina","ano":"2002","mes":"6","escola_id_escola":"1"}]
But when i try to read the code inside the JSON/Javascript, it gives me the error of UNDEFINED.
I would like to get some of your help so i can solve this problem and keep working in my project.

First of all, your edit_v.php file is not outputting valid JSON due to the line that prints the connection status of the database.
If you want to do that then you'll have to output all the data as part of an array.
For example:
header('Content-type: application/json');
$res = array(
'success' => false,
'errors' => array(),
'data' => null
);
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo")
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
// echo "Base de dados conectada!";
$res['success'] = true;
$res['data'] = array();
while ($row = $result->fetch_assoc())
{
$res['data'][] = $row;
}
}
else
{
$res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}
echo json_encode($data);
Also, the Content-Type header has to be set before any output is made.
In the complete function of your JQuery request, you are converting the JSON data to a String using JSON.stringify(...) which should not be. You should try changing the complete function to success and use the data as is.
...
success: function(data) {
console.log(data[0].marca);
},
...

Problem is with JavaScript and PHP JSON.
When there is only one element in array, there is no record zero.
Please use code: console.log(data.marca) instead of console.log(data[0].marca) and you will see result.
You have to check if in JSON is just one element array or few and then use proper code.

Solved
finally I solved my problem with the help of this big community!
Editar_v.php jquery:
$("#procuraveiculo").on('click', function() {
var e = document.getElementById("dropdown_matricula");
var strUser = e.options[e.selectedIndex].text;
alert(strUser);
$.ajax({
method: "POST",
url: "admin_pages/veiculo_pages/edit_v.php",
data: {matriculaPHP:strUser},
success: function(data) {
var marca = data[0].marca;
var modelo = data[0].modelo;
var cilindrada = data[0].cilindrada;
var potencia = data[0].potencia;
var combustivel = data[0].combustivel;
var ano = data[0].ano;
var mes = data[0].mes;
var idEscola = data[0].escola_id_escola;
And now, the PHP file: edit_v.php:
<?php
header('Content-type: application/json');
$res=array(
'success' => false,
'errors' => array(),
'data' => null
);
$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);
if($conn->query($sql) == TRUE)
{
// echo "Base de Dados conectada!";
$res['success'] = true;
$res['data'] = array();
while($row = $result->fetch_assoc())
{
$res['data'][] = $row;
}
}
else
{
$res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}
echo json_encode($res['data']);
?>
This is working very well, and now I do understand how jquery works in this situations. Also understood what was my fault in PHP.
My thanks to #Omari Celestine and #Norbul and to stackoverflow community.

Related

How to select value based on previous 2 input field in php

I have 3 select fields. Now based on 1st one I need to select 2nd and 3rd. but the problem is I need 2nd field value as a where condition in sql query for 3rd field. I am able to select value for 2nd and 3rd on the basis for 1st one but not able to put where condition on the basis of 2nd field.
For more clarity below is my PHP code.
<div class="form-row">
<div class="form-group col-md-4">
<label>Employee Code*</label>
<?php
$sql = "select * from issue where status like '%not%' ";
$stmt = $conn->prepare ( $sql );
$result = $stmt->execute();
// $row = $stmt->fetch ( PDO::FETCH_ASSOC );
echo '<select class="custom-select form-control"
name="employeecode"id="employeecode"onChange="getin(this.value),geti(this.value),getinfoa(this.value)" required>';
echo '<option value="">'.'</option>';
foreach($stmt as $row){
echo '<option value ="'.$row['employeecode'].'">'.$row['employeecode'].'</option>';
}
echo '</select>';
?>
</div>
<div class="form-group col-md-4 ">
<label>Employee Name*</label>
<input class="form-control" placeholder="Employee Name" name="employeename" type="text" id="employeename" required>
<div class="invalid-feedback">This field is requires</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label>Category*</label>
<select class="custom-select form-control" name="cat" id="cat" onChange="info(this.value)"required>
</select>
</div>
<div class="form-group col-md-4">
<label>Issue No.*</label>
<select class="custom-select form-control" name="issue_id" id="issue_id" onChange="getinfo(this.value)" required>
</select>
</div>
</div>
Now when I select employee code it will automatically fill the category and Issue No. But now I also want to pass category value to Issue No so that issue no come on the basis of employee code and category.
Below is the script code:
<script>
function geti(employeecode){
var employeecode = $('#employeecode').val();
//alert(employeecode);
$.ajax({
url:'populate_subcategory.php',
type:"POST",
data:"name="+employeecode+"&type=employeecode",
cache: false,
dataType: 'json',
success: function(response){
$('#cat').empty();
$('#cat').append("<option></option>")
for (var i = 0; i < response.length; i++) {
//alert(response);
$("#cat").append('<option value=' + response[i] + '>' + response[i] +'</option>');
}
}
});
}
function getinfoa(employeecode){
var employeecode = $('#employeecode').val();
//alert(employeecode);
$.ajax({
url:'subcategory.php',
type:"POST",
data:"name="+employeecode+"&type=employeecode",
cache: false,
dataType: 'json',
success: function(response){
$('#issue_id').empty();
$('#issue_id').append("<option></option>")
for (var i = 0; i < response.length; i++) {
//alert(response);
$("#issue_id").append('<option value=' + response[i] + '>' +
response[i] +'</option>');
}
}
});
}
</script>
PHP file for script:
<?php
if($type=='employeecode')// for category
{
$name=($_POST['name']);
$data = array();
$sql = "select * from issue where status like '%Not%' and employeecode = '$name' ";
$stmt = $conn->prepare ( $sql );
$result=$stmt->execute();
foreach($stmt as $row){
array_push($data, $row['cat']);
}
echo json_encode($data);
}
if($type=='employeecode')// for issue No
{
$name=($_POST['name']);
$data = array();
$sql = "select * from issue where status like '%Not%' and employeecode =
'$name'";
$stmt = $conn->prepare ( $sql );
$result=$stmt->execute();
foreach($stmt as $row){
array_push($data, $row['issue_id']);
}
echo json_encode($data);
}
?>
Now I want sql query for issue No like this :
$sql = "SELECT * FROM issue WHERE status LIKE '%Not%' AND employeecode =
'$name' AND cat='category selected'";
Please help me to understand the same.

how can I send AJAX request in OOP?

I have form like this.
<form action="Barang.php" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-md-3"
for="id_suplier">ID suplier :</label>
<div class="col-md-5">
<select class="selectpicker" title="Ketikkan ID suplier" data-width="100%" data-live-search ="true" id="id_suplier" autocomplete="off" onchange="" required>
<?php
$query = $db->query('SELECT * FROM tb_suplier');
?>
<?php
while($row = $query->fetch(PDO::FETCH_ASSOC)){ ?>
<option value="<?php echo $row['id_suplier']; ?>"><?php echo $row['id_suplier']; ?></option>
<?php
}
?>
</select>
</div>
<span class="badge badge-info" style="margin-top:10px;" id="namasup">nama suplier</span>
</div>
</form>
<script type="text/javascript">
$('#id_suplier').on('change', function() {
var id_suplier=$("#id_suplier").val();
$.ajax({
type:"POST",
url:"Barang.php",
dataType:'json',
success:function(data) {
$("#namasup").html(data.namasup);
}
});
})
</script>
And I want send the request to Barang.php, and I want to process in getSuplier(), and get name suplier to database and put the value on id=namasup. how can I process it?
And here code Barang.php
<?php
class Barang
{
function getSuplier($id){
$query = $this->db->query("SELECT nama from tb_suplier where id='$id' ");
$result=$query->fetch(PDO::FETCH_ASSOC);
return $result;
}
}
Maybe you can do this
class Barang
{
function getSuplier($id){
// your code here ....
}
}
$barang = new Barang;
$barang->getSupplier($_GET['id']);
In addition to that, Jeff is right. You are not sending your id_suplier to the server. Please send it.
I think you no need to request name from database every time you change data in selection
In my opinion you can use this code
in html
<html>
<body>
<form action="Barang.php" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-md-3"
for="id_suplier">ID suplier :</label>
<div class="col-md-5">
<select class="selectpicker" title="Ketikkan ID suplier" data-width="100%" data-live-search ="true" id="id_suplier" autocomplete="off" onchange="" required>
</select>
</div>
<span class="badge badge-info" style="margin-top:10px;" id="namasup">nama suplier</span>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function createOption(datas)
{
var html = "";
for (var i in datas){
var data = datas[i];
html = html + '<option value="'+data['id']+'">'+ data['name'] +'</option>';
}
return html;
}
$(document).ready(function() {
//get all data
$.ajax({
type:"POST",
url:"Barang.php",
type: "json",
//dataType:'json',
success:function(res) {
var datas = JSON.parse(res);
$("#id_suplier").html(createOption(datas));
//tigger change event
$('#id_suplier').change();
}
});
$('#id_suplier').on('change', function(){
//change name in span
var name = $('#id_suplier').find(":selected").text();
$("#namasup").html(name);
});
});
</script>
</body>
in php
class Barang
{
//Method for get all datas
public function getSupliers(){
//I don't have you database so I skip this part
// $query = $this->db->query("SELECT nama from tb_suplier");
// $result=$query->fetch(PDO::FETCH_ASSOC);
// return $result;
//mock data
$datas = [[
'id' => 1,
'name' => 'Test 1',
],[
'id' => 2,
'name' => 'Test 2',
],[
'id' => 3,
'name' => 'Test 3',
]];
return $datas;
}
}
$class = new Barang();
$datas = $class->getSupliers();
echo json_encode($datas);
Hope this help

JavaScript error and database update

I have a problem with my database and doing the update of it. I have a database table stock with 5 columns (stock_id, p_id, brand_id, cat_id, availability). I want to do an update from the frontend. So when the popup show up and I fill in the form, UPDATE doesn't work. I have 3 files. First one stock.php that read database and works fine. the seconf one that open if you click edit looks like this:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM stock WHERE stock_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
$brand_id = $row['brand_id'];
$p_id = $row['p_id'];
?>
<form method="post" name="form">
<input id="stock_id" name="stock_id" type="hidden" value="<?php echo $row['stock_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND</label>
<select id="brand" name="brand" class="switchable form-control">
<?php
$qex = "SELECT * FROM brand";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['brand_id']; ?>"<?php
if ($brand_id == $rowex['brand_id'])
echo 'selected'; ?> class="brand_<?php echo $rowex['cat_id'];?>"><?php echo $rowex['brand_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">PRODUCT NAME</label>
<select id="product" name="product" class="switchable form-control">
<?php
$qex = "SELECT * FROM product";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['product_id']; ?>"<?php
if ($product_id == $rowex['product_id'])
echo 'selected'; ?> class="product_<?php echo $rowex['brand_id'];?>"><?php echo $rowex['product_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">IN STOCK</label>
<input type="number" id="availability" name="availability" value="<?php echo $row['availability'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var stock_id = $("#stock_id").val();
var category = $('select[name="category"]').val()
var brand = $('select[name="brand"]').val()
var product = $('select[name="product"]').val()
var availability = $("#availability").val();
var dataString =
'stock_id='+ stock_id +
'&brand=' + brand +
'&category=' + category +
'&product=' + product +
'&availability=' + availability
;
if(
stock_id=='' ||
brand=='' ||
category=='' ||
product=='' ||
availability==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-stock.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
$("#category").change(function () {
if ($(this).data('options') == undefined) {
$(this).data('options', $('select.switchable option').clone());
}
var id = $(this).val();
var that = this;
$("select.switchable").each(function () {
var thisname = $(this).attr('name');
var theseoptions = $(that).data('options').filter('.' + thisname + '_' + id);
$(this).html(theseoptions);
});
});
//then fire it off once to display the correct elements
$('#category').trigger('change');
});/** Document Ready Functions END **/
</script>
<?php } ?>
This is my code for update-stock.php that supposed to be updating the database:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$stock_id = $_POST['stock_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$availability = $_POST['availability'];
$update = array(
'p_id' => $product,
'brand_id' => $brand,
'cat_id' => $cat,
'availability' => $availability
);
$where_clause = array(
'stock_id' => $stock_id
);
$updated = $database->update( 'stock', $update, $where_clause, 1 );
}
?>
I have a 2 problems.
Update doesn't work at all. I am just getting the message Please Enter Valid Data
My form doesn't show up the correct value of the PRODUCT NAME. Example: In the database and my main table that read information from database product name is 2.1.1 but when I click on edit and open my pop-up form that show up 2.1.3 for example.
Thank you so much in advance for your help.
This one works PERFECT fetch_brand.php:
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
$query = "SELECT * FROM brand WHERE brand_id = $id";
$results = $database->get_results( $query );
foreach( $results as $row ){
$cat_id = $row['cat_id'];
?>
<form method="post" name="form">
<input id="brand_id" name="brand_id" type="hidden" value="<?php echo $row['brand_id'];?>"/>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">CATEGORY</label>
<select id="category" name="category" class="form-control">
<?php
$qex = "SELECT * FROM category";
$rex = $database->get_results( $qex );
foreach( $rex as $rowex ) {
?>
<option value="<?php echo $rowex['cat_id']; ?>"<?php
if ($cat_id == $rowex['cat_id'])
echo 'selected'; ?>><?php echo $rowex['cat_name'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">BRAND NAME</label>
<input type="text" id="brand_name" name="brand_name" value="<?php echo $row['brand_name'];?>" class="form-control"/>
</div>
</div>
<div class="clearfix"></div>
<div>
<input type="submit" value="Update Data" class="pull-right btn btn-primary submit" style="margin-right:15px;"/>
<span class="pull-left error" style="display:none;margin-left:15px;"> Please Enter Valid Data</span>
<span class="pull-left success" style="display:none;margin-left:15px;"> Data updated!</span>
<div class="clearfix"></div>
</div>
</form>
<?php
}
?>
<script type="text/javascript" >
$(document).ready(function(){
$(function() {
$(".submit").click(function() {
var brand_id = $("#brand_id").val();
var brand_name = $("#brand_name").val();
var category = $('select[name="category"]').val()
var dataString =
'brand_id='+ brand_id +
'&brand_name=' + brand_name +
'&category=' + category
;
if(
brand_id=='' ||
brand_name=='' ||
category==''
){
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update-brand.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
});/** Document Ready Functions END **/
</script>
<?php } ?>
update-product.php :
<?php
session_start();
include ( 'config.php' );
require_once( 'class.db.php' );
$database = DB::getInstance();
if($_POST) {
$p_id = $_POST['p_id'];
$brand = $_POST['brand'];
$category = $_POST['category'];
$product = $_POST['product'];
$update = array(
'product_name' => $product,
'brand_id' => $brand,
'cat_id' => $cat
);
$where_clause = array(
'p_id' => $p_id
);
$updated = $database->update( 'product', $update, $where_clause, 1 );
}
?>
This one works excellent! So I am pretty sure that I made a mistake in my code for the stock.

unable to fetch data in multiple dropdown

I am unable to fetch the data in the second dropdown(which is depended upon the first dropdown). e.g. when we select country then the relevant state should be displayed but it doesn't. see my code.
my html
<?php
require 'dbconfig.php';
?>
<label class="control-label">Select Distict</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=dist id=dist>
<option value='' selected>Select</option>
<?Php
$ddObj = new USER($DB_con);
$table= "tbl_dist";
$sel = $ddObj->dropdowndist($table);
foreach ($sel as $val) {
echo "<option value=$val[dist_id]>$val[dist_name]</option>";
}
?>
</select>
</div>
</div>
<label class="control-label">Select Block</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=block id=block>
</select>
</div>
</div>
my jquery
<script>
$(document).ready(function() {
$('#dist').change(function(){
var dist_id=$('#dist').val();
$('#block').empty(); //remove all existing options
$.get('ddblock.php',{'dist_id':dist_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#block").append("<option value='" + value.block_id +"'>"+value.block_name+"</option>");
});
}, "json");
});
});
</script>
ddblock.php
<?Php
$dist_id=$_GET['dist_id'];
if(!intval($dist_id)){
echo "Data Error";
exit;
}
require 'class.user.php';
$ddObj = new USER($DB_con);
$table = "tbl_block";
$result = $ddObj->fetch_block($table,$dist_id);
$main = array('data'=>$result);
echo json_encode($main);
}
?>
class.user.php
public function fetch_block($table,$dist_id){
try
{
$sel = $this->db->prepare("SELECT * FROM $table WHERE block_dist_id=:dist_id");
$sel->bindValue(':dist_id', $dist_id);
$sel->execute();
$rs = $sel->setFetchMode( PDO::FETCH_ASSOC );
return $sel;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}

automatically populate text box based on select entry

Is there a way within php to get a value picked up from database automatically?
Basically, If I have a select box & I select option "Laptop-01" , is there a way within PHP to check the database for that row and then automatically pick up the serial number of Laptop-01 and populate it within the text box for the devices serial number.
At the moment I've just got two text boxes and user would need to manually enter both the product number (Laptop-01) & then the serial number.
I've currently got the following code;
PHP
<?php
$selectquery = "SELECT * FROM `loanproducts`";
$selectresult = mysqli_query($connection, $selectquery);
$selectusersquery = "SELECT * FROM `loanusers`";
$selectusersresult = mysqli_query($connection, $selectusersquery);
if (isset($_POST['editloan'])):
$loanid = $_POST["loanid"];
$username = $_POST["username"];
$product=$_POST["product"];
$product_desc=$_POST["product_desc"];
$serial=$_POST["serial"];
$date_collected=$_POST["date_collected"];
$date_return = $_POST["date_return"];
$returned = $_POST["returned"];
$edit_query="UPDATE loans SET
username = '$username',
product = '$product',
product_desc = '$product_desc',
serial = '$serial',
date_collected ='$date_collected',
date_return = '$date_return',
returned = '$returned'
WHERE loanid ='$loanid'";
$edit_result= mysqli_query($connection, $edit_query);
if ($edit_result) :
header ('location: editloan.php?confirm=Loan successfully updated');
else :
echo "<b>This didn`t work, error: </b>";
echo mysqli_error($connection);
endif;
endif;
$loanid=$_GET['loanid'];
$my_query="select * from loans where loanid=$loanid";
$result= mysqli_query($connection, $my_query);
while ($myrow = mysqli_fetch_array($result)):
$username = $myrow["username"];
$product = $myrow["product"];
$product_desc = $myrow["product_desc"];
$serial = $myrow["serial"];
$date_collected=$myrow["date_collected"];
$date_return=$myrow["date_return"];
$returned=$myrow["returned"];
endwhile;
?>
HTML
<html>
<h2 align="center">Edit Product Form</h2>
<body>
<div id="loginp"<p align="center">Edit this loan for the Coleg Sir Gar Loan System</p></div>
<form method="POST" action="editloaninfo.php">
<div id="editp"><p align="center">
<label class="labelform">Username:</label><select name="username" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectusersresult))
{ if ( $row1[1] == $username )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product:</label><select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult))
{ if ( $row1[1] == $product )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product Description:</label><input class="inputform" type="text" name="product_desc" placeholder="Product Description..." autocomplete="off" required size="18" value="<?php echo $product_desc; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Serial Number:</label><input class="inputform" type="text" name="serial" placeholder="Serial Number..." autocomplete="off" required size="18" value="<?php echo $serial; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Collected:</label><input class="inputform" type="date" name="date_collected" autocomplete="off" size="30" value="<?php echo $date_collected; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Returned:</label><input class="inputform" type="date" name="date_return" autocomplete="off" size="30" value="<?php echo $date_return; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Returned:</label><select name="returned" style="width: 150px">
<option value="Yes" <?php echo $returned === 'Yes' ? 'selected="selected"' : '' ?>>Yes</option>
<option value="No" <?php echo $returned === 'No' ? 'selected="selected"' : '' ?>>No</option>
</select></p></div>
<br>
<input type="hidden" name=loanid value= "<?php echo $loanid; ?>" >
<div id="editp"><input class="inputform" type="submit" name="editloan" value="Save Changes">
<input class="inputform" type="button" name="Cancel" value="Cancel" onClick="window.location.href='editloan.php'"></div>
</form>
</body>
</html>
</div>
Basically you want to do is :
When User select 'Laptop-01' you page must update all INPUTS with information related to user's laptop (like Serial number).This can be done by adding AJAX
Please note : This answer will give you idea about how to Populate data from data base then you can do this for any information you needed.
<form>
<select id='product_name' onchange="get_data()">
<option value='Laptop-01'>Laptop-01</option>
</select>
<input name='serial_no' id='serial_no'>
<input name='product_no' id='product_no'>
</form>
<script src="js/ajax.js"></script>
<script>
function get_data(){
//In very short what this do is :
//get values
var serial_no = document.getElementById('product_name').value;
//create an Object
var ajax = ajaxObj("POST", "yourpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
//ajax.responsetex is things you echo from script next to it
var index1 = ajax.responseText.split(",");
//index1 is array holding values
//index1[0]=$serial_no
//index1[1]=$product_no
//Now set value of your serian_no INPUT to $serial_no = index1[0];
document.getElementById('serial_no').value = index1[0];
document.getElementById('product_no').value = index1[1]
}
}
//ajax.send = POST/GET method
ajax.send("product_name="+product_name);
}
</script>
<?php
if(isset($_POST['product_name'])){
$sql = "SELECT serial_no,product_no FROM loanuser WHERE username='$username'";
$query = ($connection , $query);
while ($myrow = mysqli_fetch_array($query)){
$serial_no = $myrow["serial_no"];
$product_no = $myrow["product_no"];
}
//form a (,) separated list and echo it.
echo $serial_no.",".$product_no;
exit();
}
?>
Ajax.js
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
If you want me to add more explanation on AJAX used in this page , please add request in comment section i will edit it to more better answer

Categories

Resources