简体   繁体   中英

Select on change/submit inside Ajax

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM