Set input value upon select option in php - php

I have a form where I am selecting a product. On the basis of the selected product, I want to update the rest of the fields in the form.
The Form display with select option
On selecting the product name, I want rest of the details of the form to fill up from the database using php.
Here is the code for the table created.
<table id="productTable" class="table-c">
<tr>
<th class="text-center" style="width: 5%;">SR No.</th>
<th class="text-center" style="width: 45%">DESCRIPTION</th>
<th class="text-center" style="width: 10%">HSN/SAC</th>
<th class="text-center" style="width: 10%">QTY IN-HAND</th>
<th class="text-center" style="width: 10%">ENTER OUTWARD QTY</th>
<th class="text-center" style="width: 5%">Delete</th>
</tr>
<tr style="text-align: center;" id="products">
<?php $j=0; $j++; ?>
<td><?php echo $j; ?></td>
<td><select class="form-control" name="code" id="productID" style="width: 429px;">
<?php
$sql = "SELECT * FROM `product`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option id='".$row['code']."' value='".$row['pname']."'>".$row['pname']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
<td><input type="number" name="hsnNo" id="hsnNo" readonly></td>
<td><input type="number" name="qty" id="qty" readonly></td>
<td class="coljoin"><input type="number" format="2" name="amount"></td>
<td>
<span class="fa fa-trash"></span>
</td>
</tr>
</table>
How should I do this?

This is PHP Code:-
<form>
<select name="customer" id="customer_id">
<option value="">-- Select customer Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
Address: <input name="add" type="text" value="">
Mobile: <input name="mobile" type="text" value="">
EMail-Id:<input name="email" type="text" value="">
</form>
This is JS Code:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#customer_id").change(function() {
var id = $(this).val();
var dataString = 'cid='+id;
//alert(dataString);
$.ajax({
url: 'dataAjax.php',
type: 'post',
data: dataString,
success: function(response) {
// Parse the jSON that is returned
var Vals = JSON.stringify(response);
// These are the inputs that will populate
$("input[name='add']").val(Vals.add);
$("input[name='mobile']").val(Vals.mobile);
$("input[name='email']").val(Vals.email);
}
});
});
});
</script>
This is other PHP File Code:-
<?php
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("add"=>'India',"mobile"=>'1234567890','email'=>'demo#demo.com'));
}
?>

using product id use ajax & call the get_product_details(id) & in get product convert response array in json & echo it .in ajax, response data you have to parse in json... then set you required field.. (add require js)
**Ajax Call :**
$(document).on('change','your_dropdown_filed_id',function()
{
var product_id = $(this).val();
//Ajax call
$.ajax({
method: "POST",
url: "/get_product_details", //your php file function path
data: { product_id: product_id}
}).done(function( response ) {
alert( "Data Saved: " + response );
var obj = JSON.parse(response);
//obj hold all values
alert(obj.qty);
alert(obj.hsn);
$('#hsn_id').val(obj.hsn);
$('#qty_id').val(obj.qty);
});
});
**product.php**
function get_product_details(product_id)
{
//Get product details in associative array format
echo json_encode($product_details);
}

Once the product is selected execute ajax request and get data from the database with respective of the selected product.
JAVASCRIPT CODE :
$('#products').change(function(){
$.ajax({
url: 'your php code page name which returns product details.php?product_id'+$('#products').val(),
type: 'post',
success: function(response) {
var obj = JSON.parse(response);
$("#hsn_sac").val(obj.hsn_sac); // hsn or sac values
$("#qty_in_hand").val(obj.qty_in_hand); // qty_in_hand values
}
}});
});
PHP CODE :
<?php
// first connect database and then fire the query to get product details
$connection = mysql_connect("your database host name","database username","database password","database name");
$result = mysql_query("your query");
while ($row = mysql_fetch_array($result)) {
// get data and store in array
}
mysql_close($connection); // close connection
echo json_encode(database result); // encode database result so that it will available to ajax request and assign back to view
exit;
?>

Related

Dynamically Populating each rows from database using php-Ajax

I have a table that is dynamically populated from mysql database.User are expected to select a staff number, which automatically goes to the DB and fetches his staff number.I have like 10rows. it works fine for the first row but not the subsequent other others.
Please, take a look at the code and advice where I am missing it.
Thanks
<tr>
<th nowrap="nowrap">S/N</th>
<th nowrap="nowrap">VNO</th>
<th nowrap="nowrap">Name</th>
<th nowrap="nowrap">Staff No</th>
</tr>
<tr>
<?php
$c=0;
$st =mysqli_query($connection,"SELECT * FROM tab_flt WHERE mainloc='".$_SESSION['location']."' AND status='Active'");
while($r = mysqli_fetch_array($st)){ $c++?>
<td><?php echo $c;?></td>
<td><input type="text" name="flt[]" value="<?php echo $r['fltno'];?>" class="form-control" readonly="readonly" /></td>
<td><select name="opname[]" class="form-control" id="subloc">
<option>Select...</option>
<?php
$fs = getOperators($_SESSION['location']);
while($f = mysqli_fetch_array($fs)){?>
<option value="<?php echo $f['name'];?>"><?php echo $f['name'];?></option>
<?php };?>
</select></td>
<td id="staffno"></td>
</tr>
Ajax side:
<script type="text/javascript">
$(document).ready(function() {
$("#subloc").change(function(){
var sname = $("#subloc option:selected").val();
$.ajax({
type:"POST",
url:"process-opno.php",
data:{opname:sname}
}).done(function(data3){
$("#staffno").html(data3);
});
});
});
</script>
The above fetches the first rows when subloc id is selected successfully into staffno id.
But it does not do it for the remaining lines. What can i do so, that it will recognise the second line, third line etc and fetches the corresponding staff number into the staffno id .
Thanks.
Please try this:
PHP Part I have added classes for select box and select box ajax result
<tr>
<?php
$c=0;
$st =mysqli_query($connection,"SELECT * FROM tab_flt WHERE mainloc='".$_SESSION['location']."' AND status='Active'");
while($r = mysqli_fetch_array($st)){
$c++;
?>
<td><?php echo $c;?></td>
<td><input type="text" name="flt[]" value="<?php echo $r['fltno'];?>" class="form-control" readonly="readonly" /></td>
<td>
<select name="opname[]" class="form-control js-sel-box" data-id="<?php echo $c;?>">
<option>Select...</option>
<?php
$fs = getOperators($_SESSION['location']);
while($f = mysqli_fetch_array($fs)){
?>
<option value="<?php echo $f['name'];?>"><?php echo $f['name'];?></option>
<?php
};
?>
</select>
</td>
<td class="js-sel-box-ajax-result-<?php echo $c;?>"></td>
<?php
}//End While
?>
</tr>
Ajax Part:
<script type="text/javascript">
$(document).ready(function() {
$(".js-sel-box").change(function(){
var sname = $(this).val();
var result_id = $(this).attr("data-id");
$.ajax({
type:"POST",
url:"process-opno.php",
data:{opname:sname}
}).done(function(data3){
$(".js-sel-box-ajax-result-"+result_id).html(data3);
});
});
});
</script>
The same old problem with unique ids, change the id into a class,find all your elements based on the changed select
<script type="text/javascript">
$(document).ready(function() {
$("td select.form-control").change(function(){
var sname = $(this).val();
var el = $(this);
$.ajax({type:"POST",url:"process-opno.php",data:{opname:sname}})
.done(function(data3){
$(this).parent().next("td").html(data3);
});
});
});
</script>
Yes, its better to use class identifier instead of id to identify multiple DOM elements; but in yours it can be workable with minimum changes-
// use
var sname = $(this).val();
//put this line just var sname
var $object =$(this);
// instead of
var sname = $("#subloc option:selected").val();
// this is because- $('#subloc option:selected').val(); always returns the first
//dropdownList/optionlist from the DOM array, you can use `this` to track which DOM has been change recently
// another change in your code $object is $(this) equivalent but will not work inside ajax so you need to create $object as in code above..
// put this line
$($object).parents('tr').find("#staffno").html(data3);
//instead of
$("#staffno").html(data3);
// above line will search parent tr and will look for DOM element with id staffno a

How to send multiple same name input fields value via ajax post method

I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display

Get data from php-foreach-loop to ajax

I have searched very long for a solution to this problem but could not find any.
I get data from the database to show some projects on my website. For each project i can click on a pen-symbol to edit the name of the project. I´d like to send the date per ajax request, but always get the data of the first project. If i try for example to edit the name of the second project "test", i get the data of the first project "blubb"
What i have tried:
- Used classes not Id´s
Call Ajax function from PHP foreach with form
- Used $this
Get Ajax variable from the PHP foreach loops
My code lookes like this (simplified):
< script type = "text/javascript" >
$(document).ready(function() {
$(".submit").click(function() {
//here are the problems, i only get the value of the first project
var new_project_name = $('.new_project_name').val();
var old_project_name = $('.old_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
old_project_name: old_project_name,
new_project_name: new_project_name,
name: name
},
}).
done(function(response) {
blabla
});
});
}); < /script>
<?php foreach($db->query('SELECT * FROM portfolio ORDER BY position, id desc') as $row) { $name = $row['name']; ?>
<div class="rename">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Projektname:</td>
</tr>
<tr>
<td>
<input type="text" class="new_project_name" value="<?php echo $name;?>">
</td>
<input type="text" class="old_project_name" value="<?php echo $name;?>" hidden>
</tr>
<tr>
<td>
<input class="submit" type="submit" value="Umbenennen">
</td>
</tr>
</table>
</div>
<?php } ?>
Thank you for any help.
you could pass the id of the project to ajax and update the new value. For that you just need to pass the id of the element.
HTML
<input type="text" class="new_project_name" value="<?php echo $name;?>" rel="<?php echo $id; ?>">
jQuery
$(document).ready(function() {
$(".submit").click(function() {
var parentObj = $(this).closest('.rename');
var id = parentObj.find(' .new_project_name').attr('rel');
var project_name = parentObj.find(' .new_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
project_name : project_name ,
id:id
},
}).
done(function(response) {
blabla
});
});
});
See the Fiddle and check console
http://jsfiddle.net/hoja/2caukhvo/11/

Get Ajax variable from the PHP foreach loops

I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.

Working with checkbox which is creating by Ajax

I am working with ajax project.
I have a form of user in with name, address , postcode .
on entering the name, address or postcode the matching rows is shown by ajax file in .
so on select the checkbox i want to do some further activity.
my html code is
Address : <input type="text" name="user_name" id="from_location" value="" class="in_form" />
<div id="user"></div>
and jQuery code is
$.ajax({
url: "ajax_user.php",
data: {
address: address,
},
dataType: "html",
type: "POST",
success: function(result){
$("#user").append(result);
}
})
}
and ajax user php is
$sql= "SELECT * FROM instructor_mst WHERE sex='$sex' AND car_type='$car_type' AND address Like '%$address%' ";
if (!$sqli=mysql_query($sql)){
echo mysql_error();
}
$num_rows= mysql_num_rows($sqli);
if($num_rows != 0)
{?>
<table border="0" class="form_ins" >
<?
while ($row = mysql_fetch_array($sqli))
{
?>
<tr>
<td>
</td>
<td>
Name
</td>
<td>
Address
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="select" value"<?php echo $row['id'];?>">
</td>
<td>
<?php echo $row['name'];?>
</td>
<td>
<?php echo $row['address'];?>
</td>
</tr>
</table
<?}
in result i got like
checkbox | user name | address
now on selecting the checkbox i want to submit for other activity....
I am not getting how can i do this...All answer will be appreicieted
As your checkbox being dynamically added -
$(document).on('change','input[type=checkbox]',function(){
if($(this).is(':checked')){
// do something
}
});
Or if you have an ID of your checkbox -
$(document).on('change','#checkBoxID',function(){
if($(this).is(':checked')){
// do something
}
});
you need to delegate the click event using on for dynamically added element which is checkbox in your case
$(document).on('click','input[name="select"]',function(){
//this is called when you select the checkbox
//do your stuff
})
or delegating it to the closest static element
$('#user').on('click','input[name="select"]',function(){
//dou your stuff
});
updated
checkbox might have multiple values so to get all the values that is checked you need to loop through the values or use map()
try this
$('#user').on('click','input[name="select"]',function(){
var selectedValue = $("input[name='select']:checked").map(function(n){
return this.value;
});
console.log(selectedValue ); //this will print array in console.
alert(seletedValue.join(',')); //this will alert all values ,comma seperated
});

Categories