Reputation: 276
I have one selection option which display value 1 to 5. Based on the value selected, it will generated select option based on the number selected. let say i select 3, then it will generated 3 select option. Its possible to loop the ajax in jquery something like this Here is my div
<select name="noAffected" class="form-control noAffected" id="noAffected" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div class="form-group affectedsec1" id="affectedsec1">
<div>
<div class="form-group affectedsec2" id="affectedsec2">
<div>
<div class="form-group affectedsec3" id="affectedsec3">
<div>
<div class="form-group affectedsec4" id="affectedsec4">
<div>
and below is my jquery
$(".noAffected").change(function(){
var val=$(this).val();
alert(val);
for (var i = 1; i < val; i++)
{
alert(i);
$.ajax
({
type: "POST",
url: "getdata.php",
data: {i:i},
cache: false,
success: function(data)
{
$(".affectedsec"+i).html(data);
}
});
}
});
this ajax can be done by single call of ajax. But im wondering to have a loop in it.. below is my getdata.php
$rows = $progs->fetchAll();
echo '<label class="col-sm-3 control-label">Section '.$_POST["i"].'</label>';
echo '<div class="col-sm-9">';
echo '<select name="affectsec'.$_POST["i"].'" class="form-control '.$_POST["i"].'" id="affectsec'.$_POST["i"].'" required>';
echo '<option value="">Section</option>';
foreach($rows as $row)
{
echo '<option value="'.$row['dpt_id'].'" >'.$row['dpt_name'].'</option>';
}
echo '</select>';
echo '</div>';
Upvotes: 0
Views: 454
Reputation: 447
Don't loop the ajax
request. Instead loop inside the PHP
file.
HTML:
<select name="noAffected" class="form-control noAffected" id="noAffected" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div id="output"></div>
JQUERY:
<script>
$("#noAffected").on('change', function(){
$.ajax({
type: "POST",
url: "getdata.php",
data: { value: $(this).val() },
cache: false,
success: function(data) {
$("#output").html(data.html);
}
});
});
</script>
PHP:
<?php $rows = $progs->fetchAll();
ob_start();
$ctr = 1;
foreach ($_POST['value'] as $v) { ?>
<div class="form-group affectedsec<?php echo $ctr; ?>" id="affectedsec<?php echo $ctr; ?>">
<label class="col-sm-3 control-label">Section <?php echo $ctr; ?></label>
<div class="col-sm-9">
<select name="affectsec<?php echo $ctr; ?>" class="form-control <?php echo $ctr; ?>" id="affectsec<?php echo $ctr; ?>" required>
<option value="">Section</option>
<?php foreach($rows as $row) { ?>
<option value="<?php echo $row['dpt_id']; ?>"><?php echo $row['dpt_name']; ?></option>
<?php } ?>
</select>
</div>';
</div>
<?php
$ctr++;
}
$html = ob_get_contents();
ob_end_clean();
// wp_send_json(['html' => $html]); // If using wordpress
echo json_encode(['html' => $html]); // If not using wordpress
Upvotes: 1