How to automatic fill textbox depend upon select option from drop down - php

I have created one IMS System. In that i have to create bill on order page and in order page when i select customer name from drop down than customer_address,customer_phone and gst number should automatically fill in text box.In database i have created one table named partys in that all data are available(Customer_name,Customer_address,customer_phone and gst) If anybody knows solution than please help. Below is my code
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Name</label>
<div class="col-sm-7">
<select name="customer_name" id="client" style="width:100%;">
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'stock')
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM partys";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['party_name'] ?>"><?php echo $row['party_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Address</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_address" name="customer_address" placeholder="Enter Customer Address" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Phone</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_phone" name="customer_phone" placeholder="Enter Customer Phone" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gstin" class="col-sm-5 control-label" style="text-align:left;">GSTIN</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="gstin" name="gstin" placeholder="Enter GST Number" autocomplete="off">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/create.php',
type: 'post',
// This just sends the value of the dropdown
data: {customer_name : party_name},
dataType: 'json',
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var response = JSON.parse(response);
// These are the inputs that will populate
$("#customer_address").val(response.customer_address);
$("#customer_phone").val(response.customer_phone);
$("#gstin").val(response.gstin);
}
});
});
});
</script>

create separate php file as customer.php and write following code
$content = file_get_contents("php://input");
$customer_data = json_decode($content, true);
$customer_name = $customer_data['customer_name'];
//using mysql query fetch all data of particular customer
$query = mysqli_query($dbc,"SELECT * FROM partys WHERE party_name=$customer_name");
$result = mysqli_fetch_array($query);
echo json_encode($result);
after getting this alert json response in ajax call. This will give customer data.
and modify your ajax call as
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: 'customer.php',
type: 'post',
// This just sends the value of the dropdown
data: {customer_name : party_name},
dataType: 'json',
success: function(response) {
alert(response);
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var response = JSON.parse(response);
// These are the inputs that will populate
$("#customer_address").val(response.customer_address);
$("#customer_phone").val(response.customer_phone);
$("#gstin").val(response.gstin);
}
});
});
});

Related

How to grab data and auto fill a form on change event using Ajax

What I need
I need when someone change my calendar, a php script should run in background and fetch some data and show it in the form fields accordingly. To do that, I have the following HTML code and Ajax script
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
$('#normalShiftOperator').val(result["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(result["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(result["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
<div class="form-group">
<div class="row">
<div class="col-sm text-center" id="normalShiftOaDiv" class="">
<label for="currentOa">Current OA?</label><br>
<input type="radio" name="currentOa" id="normalShiftOa" value="normalShiftOa">
</div>
<div class="col-sm" id="normalShiftOperatorNameDiv">
<label for="normalShiftOperator">Normal Shift</label>
<select class="form-control" id="normalShiftOperator" name="normalShiftOperator">
<option></option>
<option>A</option>
<option>B</option>
</select>
</div>
<div class="col-sm" id="normalShiftOperatorDurationDiv">
<label for="normalShiftOperatorDuration">Duration</label>
<select class="form-control" id="normalShiftOperatorDuration" name="normalShiftOperatorDuration">
<option></option>
<option>1</option>
<option>2</option>
</select>
</div>
<div class="col-sm">
<label for="normalShiftPinCount">Pin Count</label>
<input type="number" class="form-control" id="normalShiftPinCount" name="normalShiftPinCount" value="23">
</div>
<div class="col-sm">
<label for="normalShiftDate">Date</label>
<input type="date" class="form-control" id="normalShiftDate" name="normalShiftDate">
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" style="margin-top: 30px;" id="normalShiftUpdate" name="normalShiftUpdate">Update</button>
</div>
</div>
</div>
I want to show the php variables $normalShiftOa, $normalShiftOperatorDuration and $normalShiftPinCount in the form fields with id normalShiftOperator, normalShiftOperatorDuration, normalShiftPinCount respectively when someone change calendar. Please see the contents of supervisorEditAjax.php. How can I show these three variables into the three id fields?
I only know how to show to one single field. But if there are multiple values to be shown in multiple fields, how can we do that?
Can someone please help?
Edit 1
Contents of supervisorEditAjax.php
<?php
$normalShiftOa = "A";
$normalShiftOperatorDuration = "2";
$normalShiftPinCount = "100";
$arr = array('normalShiftOa' => $normalShiftOa, 'normalShiftOperatorDuration' => $normalShiftOperatorDuration, 'normalShiftPinCount' => $normalShiftPinCount);
echo json_encode($arr);?>
I tried to use some Json method. But it is not working
After many trial and error, I am able to show it in the respective form fields. The issue was at the Ajax part. Basically I need to parse the Json object in order to get the specific values. Replace the AJAX code as below and it works fine
< script >
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
var returnedData = JSON.parse(result); //This is the change done to the code
$('#normalShiftOperator').val(returnedData["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(returnedData["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(returnedData["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
</script>
Please read more about JSON.parse here

foreach function in JSON returning only one row

I'm trying to display more than one row from JSON response, but somehow it is returning only one row each time. Query working well on the server. Code works well if i use it without ajax/json. I'm having headache with this. what am I doing wrong here? Any help would be appreciated.
HTML
<form>
<span id="span_section_row"></span>
<hr>
<div class="row">
<div class="form-group col-lg-6">
<label for="exam_date">Select Date of Exam</label>
<input type="text" class="form-control" id="exam_date" required readonly>
</div>
<div class="form-group col-lg-6">
<label for="exam_time">Enter Exam Time(In Minutes)</label>
<input type="number" class="form-control" id="exam_time" required>
</div>
</div>
</form>
AJAX call:
$(document).on('click', '.schedule', function(){
var exam_id = $(this).attr("id");
var btn_action = 'fetch_single';
$.ajax({
url:'web-services/schedule-exam.php',
method:"POST",
data:{exam_id:exam_id, btn_action:btn_action},
dataType:"json",
success:function(data)
{
$('#setup_exam_modal').modal('show');
$('#span_section_row').html(data.section_row);
}
})
});
PHP:
if($_POST['btn_action'] == 'fetch_single')
{
$exam_type_id = $_POST['exam_id'];
$query = "
SELECT a.*, b.exam_type_name
FROM exam_section a
INNER JOIN exam_type b
ON a.exam_type_id=b.exam_type_id
WHERE a.status = :status
AND a.exam_type_id = :exam_type_id
";
$statement = $conn->prepare($query);
$statement->execute(
array(
':status' => 'active',
':exam_type_id' => $exam_type_id
)
);
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['section_id'] = $row['section_id'];
$output['exam_type_id'] = $row['exam_type_id'];
$output['section_name'] = $row['section_name'];
$output['exam_type_name'] = $row['exam_type_name'];
$output['section_row'] =
'<div class="row">
<div class="form-group col-lg-4">
<label for="select_section"></label>
<p id="select_section">'.$row['section_name'].'</p>
</div>
<div class="form-group col-lg-4">
<label for="no_of_questions">No. of Questions</label>
<input type="number" class="form-control" id="no_of_questions" required>
</div>
<div class="form-group col-lg-4">
<label for="mark_per_question">Mark Per Question</label>
<input type="number" class="form-control" id="mark_per_question" required>
</div>
</div>
';
}
echo json_encode($output);
}
First in the PHP you are overwriting the array each time round the loop so there would only ever have been one occurance passed back to the javascript to process
if($_POST['btn_action'] == 'fetch_single') {
$exam_type_id = $_POST['exam_id'];
$query = "SELECT a.*, b.exam_type_name
FROM exam_section a
INNER JOIN exam_type b ON a.exam_type_id=b.exam_type_id
WHERE a.status = :status
AND a.exam_type_id = :exam_type_id";
$statement = $conn->prepare($query);
$statement->execute(
array( ':status' => 'active',
':exam_type_id' => $exam_type_id)
);
$result = $statement->fetchAll();
foreach($result as $row) {
$htm = '<div class="row">
<div class="form-group col-lg-4">
<label for="select_section"></label>
<p id="select_section">'.$row['section_name'].'
</p>
</div>
<div class="form-group col-lg-4">
<label for="no_of_questions">No. of Questions</label>
<input type="number" class="form-control" id="no_of_questions" required>
</div>
<div class="form-group col-lg-4">
<label for="mark_per_question">Mark Per Question</label>
<input type="number" class="form-control" id="mark_per_question" required>
</div>
</div>';
$output[] = [
'section_id' => $row['section_id'],
'exam_type_id' => $row['exam_type_id'],
'section_name' => $row['section_name'],
'exam_type_name' => $row['exam_type_name'],
'section_row' => $htm
];
}
echo json_encode($output);
}
So now in the javascript you will need to process that array as RASHAN suggested
$(document).on('click', '.schedule', function(){
var exam_id = $(this).attr("id");
var btn_action = 'fetch_single';
$.ajax({
url:'web-services/schedule-exam.php',
method:"POST",
data:{exam_id:exam_id, btn_action:btn_action},
dataType:"json",
success:function(data)
{
$('#setup_exam_modal').modal('show');
//$('#span_section_row').html(data.section_row);
var t="";
$.each(data,function(index,value){
// concatenate all the occurances of the html and place on page
t += value.section_row;
})
$('#span_section_row').html(t);
}
})
});
Now you have one remaining problem that I can see and that is you are generating multiple HTML element all with the same id like here,
<p id="select_section">'.$row['section_name'].'
in multiple sections of your HTML. As I am not familiar with whats going on elsewhere in the code, possibly you dont need these id's at all and can remove them. Or you will have to make them unique on the page, or amend your javascript to select those elements some other way
From your controller you are returning data as array, you need to iterate over your response as
var append="";
$.each(data,function(i,v){
append += v.section_row;
})
$('#span_section_row').html(append);

Auto Search using Php ajax

while i am making the point of sale system i ran in to problem with the search.
when i enter the product code on the product code textbox it automatically Search and display product name and price in to the relevant textboxes using ajax and jquery and php. what i tried code i attached below. i didn't get any answer while i ran the code.please read the below code and get good solution for me as soon as possible.
Form Design
<div class="form-group">
<label for="" class="col-sm-2 control-label">Product Code</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="product_code" name="product_code" placeholder="Product Code" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Product Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="product_name" name="product_name" placeholder="product_name " required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<input type="text" class="form-control price" id="price" name="price" placeholder="price" required>
</div>
</div>
AJAX
function getProductcode() {
$('#product_code').empty();
$("#product_code").keyup(function(e) {
var q = $("#product_code").val();
$.ajax({
type: 'POST',
url: '../php/project_module/get_purchase.php',
dataType: 'JSON',
async: false,
success: function(data) {
for (var i = 0; i < data.length; i++) {
$('#product_code').append($("<option/>", {
value: data[i].product_id,
text: data[i].product_name,
}));
}
data: {
product_code: $('#product_code').val()
},
}
},
error: function(xhr, status, error) {
alert(xhr.responseText);
//
}
});
}
**get_purchase.php**
$product_code = $_POST["product_code"];
$stmt = $conn->prepare("select product_id,product_name,barcode,category,description,warrenty,product_condition,price_retail,
price_cost,discount,reorderlevel,brand
from product where barcode = ?");
$stmt->bind_param("s", $product_code);
$stmt->bind_result($product_id,$product_name,$price);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("product_id"=>$product_id,"product_name"=>$product_name,"price_retail"=>$price);
}
echo json_encode( $output );
}
$stmt->close();
The data attribute is in the wrong place of the ajax configuration.
Here is a revised version
Add this to your HTML
<p id="output"></p>
And this as your getProductCode() definition
function getProductcode() {
$("#product_code").empty();
$("#product_code").keyup(function(e) {
var q = $("#product_code").val();
$.ajax({
type: "POST",
url: "../php/project_module/get_purchase.php",
dataType: "JSON",
data: { product_code: $("#product_code").val() },
success: function(data) {
if(typeof data === 'undefined'){
return
}
$("#output").val(data[0].product_id + " : " +data[0].product_name)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
}
I pasted your code in my editor (VS Code) and it gave helpful syntax errors. Maybe it would be a good idea to look into editors with syntax highlighting and checking capabilities?

While inserting Data into MySQL using Ajax and PHP, taking limited data?

While inserting Data into MySQL using Ajax and PHP, taking limited data from rich textarea,Is there any problem?
JQuery Script
$('#adddesc').click(function(e)
{
e.preventDefault();
var txtcategoryname=tinyMCE.get('txtcategoryname').getContent();
var txttitle=$('#txttitle').val();
var selectError1=$("#selectError1").val();
var selectError2=$("#selectError2").val();
var selectError3=$("#selectError3").val();
//var fimage=$("#fimage").val();
//alert($("#selectError2").val().length);
var dataString;
var err;
err=(txttitle!='' && txtcategoryname!='' && $("#selectError1").val()!='0' && $("#selectError2").val()!='0' && $("#selectError3").val()!='0')?'0':'1';
// var dataString1="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2;
//dataString1="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2+"& subcat="+selectError3;
// alert(dataString1);
if(err=='0')
{
dataString="txttitle="+txttitle+"& description="+txtcategoryname+"& catname="+selectError1+"& tags="+selectError2+"& subcat="+selectError3;
//alert(dataString);
$.ajax({
type: "POST",
url: "aAddDescription.php",
data: dataString,
cache: true,
beforeSend: function(){ $("#adddesc").val('Adding Des.....');},
success: function(html){
//$("#txtcategoryname").val('');
tinyMCE.get('txtcategoryname').setContent('');
$("#txttitle").val('');
//$("#selectError1").get(0).selectedIndex = 0;
//$("#error").removeClass("alert alert-error");
$("#error").addClass("alert alert-success");
$("#error").html("<span style='color:#cc0000'>Success:</span> Description Added Successfully. ").fadeIn().delay(3000).fadeOut();
}
});
HTML Form script
<form class="form-horizontal" method="POST" action="" enctype="multipart/form-data" autocomplete="off">
<fieldset>
<div class="control-group">
<label class="control-label" for="selectError">Select Cateogry</label>
<div class="controls">
<?php
$result=mysqli_query($db,"SELECT * FROM categories ");
//$count=mysqli_num_rows($result);
$op="<option value='0'>Select Category</option>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$op.="<option value='".$row['id']."'>".$row['title']."</option>";
}
?>
<select id="selectError1" >
<?php echo $op; ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="selectError">Select Sub Cateogry</label>
<div class="controls">
<select id="selectError3">
<option selected="selected" value="0">--Select Sub--</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="focusedInput">Enter Title:: </label>
<div class="controls">
<input class="form-control" type="text" id="txttitle" name="txttitle" value="" placeholder="Enter Title"><span id="user-availability-status"></span> <img src="LoaderIcon.gif" id="loaderIcon" style="display:none;width:20px;height:20px;" />
</div></div>
<div class="control-group">
<textarea rows="10" cols="20" name="content" style="width:100%; height:150px" id="txtcategoryname"></textarea>
</div>
<div class="control-group">
<label class="control-label" for="selectError1">Tags(select All with Press Ctrl)</label>
<div class="controls">
<?php
$result=mysqli_query($db,"SELECT * FROM tags ");
//$count=mysqli_num_rows($result);
$op1='';
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$op1.="<option value='".$row['title']."'>".$row['title']."</option>";
}
?>
<select id="selectError2" multiple >
<?php //echo $op1; ?>
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="adddesc">Save changes</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>
aAddDescription.php
<?php
include("common/db.php");
session_start();
if(isSet($_POST['description']) && isSet($_POST['txttitle']))
{
// username and password sent from Form
$description=$_POST['description'];
$txttitle=mysqli_real_escape_string($db,$_POST['txttitle']);
$catname=mysqli_real_escape_string($db,$_POST['catname']);
$subcat=mysqli_real_escape_string($db,$_POST['subcat']);
$tags=mysqli_real_escape_string($db,$_POST['tags']);
//$fimage=$_FILES['fimage']['name'] ;
$cby=$_SESSION['login_user'];
//$result=mysqli_query($db,"SELECT * FROM categories WHERE title='$categoryname'");
//$count=mysqli_num_rows($result);
//$target_dir = "uploads/";
//$target_file = $target_dir.$_FILES['fimage']['name'];
//move_uploaded_file($_FILES['fimage']['tmp_name'],$target_file);
//$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
/*if($count>0)
{
echo "0";
}
else
{
mysqli_query($db,"INSERT INTO categories(title) VALUES('".$categoryname."')");
echo "1";
}*/
//date_default_timezone_set('Asia/Delhi');
mysqli_query($db,"INSERT INTO description(title,description,cat_id,tags_id,created,modified,createdby,modifiedby,subcat_id) VALUES('".$txttitle."','".$description."','".$catname."','".$tags."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".$cby."','".$cby."','".$subcat."')");
$cid=mysqli_insert_id($db);
$cresult=mysqli_query($db,"SELECT * FROM counter WHERE cont_id='$cid'");
$ccount=mysqli_num_rows($cresult);
if($ccount==0)
{
mysqli_query($db,"INSERT INTO counter(cont_id) VALUES(".$cid.")");
}
echo "1";
}
?>
Please help me any thing wrong in this code?...even i changed cache to false also getting same problem. if i type 1000/less or more lines data, always it is taking limited data. Please help me. thanks in Advance
I'd be willing to bet that your text has characters in it that are interfering with the url like "&", "?", "/", "=", etc.
You should encode your text with encodeURIComponent() like this:
var txtcategoryname=encodeURIComponent(tinyMCE.get('txtcategoryname').getContent());
var txttitle=encodeURIComponent($('#txttitle').val());
var selectError1=encodeURIComponent($("#selectError1").val());
var selectError2=encodeURIComponent($("#selectError2").val());
var selectError3=encodeURIComponent($("#selectError3").val());

bootstrap modal cannot assign input value

I've my call to ajax
$("#box-modal").on("shown",function(event)
{
$("#selectproductname").change(function(){
var valueProduct = $(this).val();
event.preventDefault();
$.ajax({
type:'GET',
url:'/ajax/products_ajax.php?idProducto='+valueProduct+'&opcion=2',
async:true,
datatype:'text',
success: function(data)
{
$("#editor-panel").load("/ajax/order.html");
$("#editor-actions").removeClass("hidden");
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
if(debug)
{
inputs[0].value="holaaa";
}
}
first I get the data with php, I get
1#jeans*1.00**0#100
after I want to assign this data a my order.html,
example:
inputs[1].value = jeans
inputs[2].value = 1.00
inputs[3].value = null
I get with console.log(inputs)
[item: function, namedItem: function]
0: input#inputnombre
1: input#inputidproducto
2: input#inputprecio.form-control
3: input#inputcantidad.form-control
4: input#inputdescatalogado.form-control
inputcantidad: input#inputcantidad.form-control
inputdescatalogado: input#inputdescatalogado.form-control
inputidproducto: input#inputidproducto
inputnombre: input#inputnombre
inputprecio: input#inputprecio.form-control
length: 5
When I do inputs[0].value="hello";
I get the error:
Uncaught TypeError: Cannot set property 'value' of undefined
In ajax order I have:
<div class="panel panel-body">
<form role="form" class="form-horizontal" id="form_order">
<div class="form-group">
<label for="inputnombre" class="col-md-4 col-xs-4 control-label">Nombre producto</label>
<div class="col-md-4 col-xs-4 control-label">
<input id="inputnombre" name="inputnombre" required type="text" />
<input type="hidden" name="inputidproducto" id="inputidproducto"/>
</div>
</div>
<div class="form-group">
<label for="descripciontext" class="col-md-4 col-xs-4 control-label">Descripcion</label>
<div class="col-md-4 col-xs-4 control-label">
<textarea cols="30" rows="10" id="descripciontext" name="descripciontext"></textarea>
</div>
</div>
<div class="form-group">
<label for="inputprecio" class="col-md-4 col-xs-4 control-label">Precio</label>
<div class="col-md-4 col-xs-4 control-label">
<input id="inputprecio" name="inputprecio" class="form-control" required type="text" />
</div>
How could I make the code easier?
Ajax .load takes time, you need to assign your values when .load is completed
$("#box-modal").on("shown", function(event) {
$("#selectproductname").change(function() {
var valueProduct = $(this).val();
event.preventDefault();
$.ajax({
type: 'GET',
url: '/ajax/products_ajax.php?idProducto=' + valueProduct + '&opcion=2',
async: true,
datatype: 'text',
success: function(data) {
// Ajax load takes time, you need a complete function here
$("#editor-panel").load("/ajax/order.html", function() {
// do below when "/ajax/order.html" is loaded
$("#editor-actions").removeClass("hidden");
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
if (debug) {
inputs[0].value = "holaaa";
}
});
}
});
});
});
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
jquery
var inputs = $("#editor-panel input").eq(0).val("hello");

Categories