i have an appended, there a selectbox with 2 textbox
first the selectbox will selecting an item, after on change, it will set all the textbox with data based on selected.
my select option calling data from database array $data.
this is my ajax code
function getBarang(val) {
$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type:"POST",
data:{"get_barang":val},
dataType:"JSON",
success:function(data){
$('#harga_jual').val((data[0].harga_jual));
$('#stock_sisa').val((data[0].stock_sisa));
}
});
}
this is my form
echo '<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value)">';
echo (isset($dBarang->id_barang)) ? '<option value="' . $dBarang->id_barang.'">' . $dBarang->nama_barang . '</option>' : '';
echo ' </select> ';
echo '
<input type="text" class="form-control" name="stock_sisa" id="stock_sisa">
<input type="text" class="form-control" name="harga_jual" id="harga_jual">
lets pass about query data, because its worked.
and this is my view as result
my second textbox not working, pls help me, thanks
Edited:
Let me explain more.
the target is textbox stock sisa, and textbox harga_jual
the $dBarang created like this, $row just like $i=0, for cheching last data on database
$dataBarang = $this->m_db->getDataWhere("v_pembelian_detail","id_pembelian","'$id_p' ORDER BY id_pembelian_detail");
$dataBarang = (empty($dataBarang)) ? [''] : $dataBarang;
foreach ($dataBarang as $dBarang)
{
You can pass this as well inside your function where this refer to current select-box where change has been taken place. Then , using this you can use $(el).closest('.outer').find('.harga_jual').. to add input values to required inputs only.
Demo Code :
//just for demo..
var data = [{
"harga_jual": "soemthing",
"stock_sisa": "soemthing1"
}]
function getBarang(val, el) {
/*$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type: "POST",
data: {
"get_barang": val
},
dataType: "JSON",
success: function(data) {*/
//get closest div > get input add value there..
$(el).closest('.outer').find('.harga_jual').val(data[0].harga_jual);
$(el).closest('.outer').find('.stock_sisa').val(data[0].stock_sisa);
/* }
});*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--add sme outer div-->
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
<div class="outer">
<select name="barang[]" id="barang-'.$row.'" class="s2barang form-control" onchange="getBarang(this.value ,this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" class="form-control stock_sisa" name="stock_sisa">
<input type="text" class="form-control harga_jual" name="harga_jual">
</div>
this is what i get from changing my id to class
function getBarang(val) {
$.ajax({
url: baseurl + "JSON/getBarang",
// url: baseurl + "JSON/getVal" + val,
type:"POST",
data:{"get_barang":val},
dataType:"JSON",
success:function(data){
$('.harga_jual').val((data[0].harga_jual));//before #harga_jual
$('.stock_sisa').val((data[0].stock_sisa));//before #stock_sisa
}
});
}
but the data seem the last selected and change to all :(
i want it each selected
Related
I have two selects, the second one is hidden and it should be shown if the first select has been changed, I checked it through on('change', function(){ ... and it is working so far. I've checked and also showed a console.log when the first select box is changed.
The main problem here is when I picked a option from the first select box, it should send some request using AJAX. I've sent some request to fetch_sections.php and it should append or add data in my second select box.
This is my updated script:
<script>
$(document).ready(function() {
$('select').material_select();
$('#school-list').on('change', function() {
$.ajax({
url: 'fetch_sections.php',
type: 'post',
dataType: 'html',
data: {parent: $(this).val() },
success: function(data)
{
$('#section-list').empty();
$('#section-list').html(data);
console.log(data);
}
});
$('#hideThis').show("slow");
});
});
</script>
This is my fetch_sections.php (working, checked with PostMan):
<?php
require '../assets/php/init.php';
if ($_POST)
{
$schoolID = Essentials::sanitize($_POST['parent']);
$fetchSQL = "SELECT `sectionid`, `name` FROM `sections` WHERE schoolid = ?";
$fetch = $conn->prepare($fetchSQL);
$fetch->execute([$schoolID]);
$fetchRes = $fetch->fetchAll(PDO::FETCH_ASSOC);
if(!$fetchRes) {
echo '
<option value="" disabled selected>Unfortunately, there is no section here.</option>
';
} else {
foreach ($fetchRes as $section)
{
echo '
<option value="'.$section['sectionid'].'"">'.$section['name'].'</option>
';
}
}
}
This is my select HTML also updated:
<div class="row margin">
<div class="input-field col s12">
<select id="school-list" name="school-list">
<option value="" disabled selected>Choose your school</option>
...
</select>
<label>School</label>
</div>
</div>
<div class="row margin" id="hideThis" style="display:none">
<div class="input-field col s12">
<select id="section-list" name="section-list">
<option value="" disabled selected>Choose your section</option>
</select>
<label>Section</label>
</div>
</div>
Update [as suggested by ccKep]:
I can now see the data that I want through console.log(data), the thing that it outputs is:
<option value="9-1">9-A...</option>, now I want to add it to my main select list but it doesn't let me.
The output should be:
<select id="section-list" name="section-list">
<option value="" disabled selected>Choose your section</option>
<option value="9-1">9-A...</option>
</select>
I am having problem passing two select to $_POST
i have two select and when i post from the first the value is not been saved ,so when i post from the second select doesn't remember the first select value ,I want to pass the first select and save the value to select.
<form method="post" action="index.php">
<select id="city" name="city" class="styled-select">
<option value="all" selected="selected">all</option>
<option value="Van">Vancouver</option>
<option value="vic">Victoria</option>
</form>
<form method="post" action="index.php">
<select id="dept" name="dept" class="styled-select">
<option value="all" selected="selected">all</option>
<option value="1">First</option>
<option value="2">Second</option>
</form>
and i am using jquery to submit the form in change
when first form submitted select does not save the value of the selected option
$(document).ready(function() {
$('#city').change(function() {
$(this).find("option[selected='true']").removeAttr('selected');
$(this).find('option:selected').attr('selected', 'true');
this.form.submit();
});
$('#dept').change(function() {
$(this).find("option[selected='true']").removeAttr('selected');
$(this).find('option:selected').attr('selected', 'true');
this.form.submit();
});
});
I noticed you were missing some commas and that you didn't pass any data. Try this instead.
$("#city").change(function()
{
var selected = $("#city").find(':selected').val();
$.ajax({
url: "index.php",
type: 'POST',
data: {
"city": selected
},
success: function(data) {
console.log("success");
}
});
});
Also, you should be able to get the value of a select via val() e.g. $("#city").val().
For normal submit:
<form method="post" action="index.php">
<select id="city" name="city" class="styled-select">
<option value="all" <?php echo $_POST['city']==="all" ? "selected" : "" ?>>all</option>
<option value="Van" <?php echo $_POST['city']==="Van" ? "selected" : "" ?>>Vancouver</option>
<option value="vic" <?php echo $_POST['city']==="vic" ? "selected" : "" ?>>Victoria</option>
</form>
I have a form that gets submitted via ajax, inside that form there are two selects. these two selects get data from mysql using php.
I want is to show the second select only when the first select has been chosen, I've tried onchange and onsubmit but didn't get it to work. ajax script keeps preventing that! i even tried passing the value of the first select vie js to php, didn't work too.
<select class="form-control" name="sel1" onchange="recMarque();" required>
<option value="" hidden selected>Choose</option>
<?php
$r=$conn->query(sprintf("select * from stock")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel1))?($d[0]==$sel1)?'selected':null:null) .'>'.$d[0].'</option>';
}
?>
</select>
<script language="Javascript">
function recMarque(){
var p1 = $("select[name=sel1]").val();
alert(p1);
return p1;
}
</script>
<?php
$s1= "<script>document.writeln(recMarque());</script>";
echo $s1;
?>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
<?php
if(!empty($s1)){
$r=$conn->query(sprintf("select * from table where x='$s1'")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel2))?($d[0]==$sel2)?'selected':null:null) .'>'.$d[0].'</option>';
}
}
?>
</select>
Static html:
<select class="form-control" name="sel1" onchange="recMarque();" required>
<option value="" hidden selected>Choose</option>
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
</select>
<script language="Javascript">
function recMarque(){
var p1 = $("select[name=sel1]").val();
alert(p1);
return p1;
}
</script>
<script>document.writeln(recMarque());</script>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
</select>
I appreciate your help
Why are you using inline javascript while you are already loading the huge file of jQuery? Use jQuery change event and wrapp your hole code inside a jQuery DOM ready event. Additionnaly why are you mixing PHP with markup and javascript, this goes in contradition of AJAX purposes and of your goal descrption. You want to show the second select after selection from first select and the content depends on selected value (which require server side fetching) then send an XMLHTTPRequest to a separate (small) file and get the response.
$('select[name=sel1]').change(function(e) {
e.preventDefault();
var value = $('select[name=sel1] option:selected').val();
var text = $('select[name=sel1]',this).text();
var urlForSelect2 = $('select').attr('data-url');
// make an AJAX call and send value, text, and all your needed variable alongside
$.ajax({
type: "GET",
url: urlForSelect2,
dataType: 'html',
data: ({value: value, text: text}),
success: function(data){
$('select[name=sel1]').append(data);
});
return false;
});
And seperate the the php responsible for creating into another file with another url (urlForSelect2 in this case):
<option value="" hidden selected>Choose</option>
<?php
// Get the values sent along AJAX request using PHP $_GET, let's say $s1
if(!empty($s1)){
$r=$conn->query(sprintf("select * from table where x='$s1'")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel2))?($d[0]==$sel2)?'selected':null:null) .'>'.$d[0].'</option>';
}
}
?>
And the markup is becoming smaller and readable like:
<select class="form-control" name="sel1" data-url="recMarque();" required>
<option value="" hidden selected>Choose</option>
<?php
$r=$conn->query(sprintf("select * from stock")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel1))?($d[0]==$sel1)?'selected':null:null) .'>'.$d[0].'</option>';
}
?>
</select>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
</select>
Here is my solution
In the first select i've put onchange="selChange", the function is as follows:
<script type="text/javascript">
function selChange(){
var val = $("#sel1").serialize();
$.ajax({
type: "POST",
url: "select.php",
data: val,
success: function(data) {
$('#sel2').html(data);
}
});
return false;
}
</script>
How do i pass the selected value in a SELECT tag with serializeArray?I tried the followng code but when i click post it empties the select tag option.
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="abc" id="title_val"/>
<select name="test" id="test">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
post
</form>
JS
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'post',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
php
<?php
echo $_POST['test'];
?>
following code works for me,
data: form.serialize();
Basically all I am trying to do is send the form data to the same location of the form.
The code should:
Get the #submit click action
Extract #email, #selection1, and #selection2's data
Hide the form #form
Display #email, #selection1, and #selection2 inside paragraph #preview
I have no JQuery experience so I am lost. I tried looking around and trying different codes but nothing would work for me.
My form code is:
<form method="post" id="form">
<div class="form-group col-lg-10 col-lg-offset-1">
<input type="email" id="email" class="form-control" name="email" placeholder="Email" />
</div>
<div class="form-group col-lg-10 col-lg-offset-1">
<select class="form-control" id="selection1">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div class="form-group col-lg-10 col-lg-offset-1">
<select class="form-control" id="selection2">
<option selected="selected">Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
</div>
<div class="form-group col-lg-offset-1 col-lg-10">
<button type="button" id="submit" class="btn btn-primary btn-lg">Sign in</button>
</div>
</form>
<p id="preview"></p>
Here is the JQUery I tried.
<script type="text/javascript">
$("#submit").click(function () {
var FormVal = {
datafield1: $('#email').val(),
datafield2: $('#field2').val()
};
$.ajax({
type: "POST",
dataType: "json",
data: FormVal,
async: false,
success: function (response) {
$('#preview').html($('#email').val() + '<br />' + $('#selection1').val()) + '<br />' + $('#selection2').val());
}
});
});
</script>
You don't have to go through all those AJAX stuffs to accomplish what you need. You can simply hide the form and then set the value to the paragraph #preview
$("#submit").click(function () {
//get value like this..
var datafield1 = $("#email").val();
//hiding the form
$("#form").hide(function () {
//setting the text to #preview
$('#preview').html(
$('#email').val() + '<br />' + $('#selection1').val() + '<br />' + $('#selection2').val());
});
});
Here is a jsfiddle link of the working code.
$('#preview').html($('#email').val() + '<br />' + $('#selection1').val()) + '<br />' + $('#selection2').val());
You have an extra parentheses in this code here: $('#selection1').val()). You can use the console of your browser to debug syntax errors.