Combinatie javascript en PHP

Overzicht Reageren

Sponsored by: Vacatures door Monsterboard

Tim Klein

Tim Klein

19/03/2019 18:42:08
Quote Anchor link
Goedenavond allemaal,

Ik gebruik onderstaande code in jacascript om een html select-form te veranderen:

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function() {
    $("#type").change(function() {
        var val = $(this).val();
        if (val == "1") {
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");
        } else if (val == "2") {
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");

        } else if (val == "3") {
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");
        } else if (val == "4") {
            $("#size").html("<option value='test'>item4: test 1</option><option value='test2'>item4: test 2</option>");
        }
    });
});

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<strong class="card-title text-dark">Meldingtype</strong>
<select id="type" style="width: 100%" class="form-control">
    <option value="1" <?php if ($Incident_Type == '1'){echo 'selected="selected"';} ?>>EHBO</option>
    <option value="2" <?php if ($Incident_Type == '2'){echo 'selected="selected"';} ?>>Waterhulpverlening</option>
    <option value="3" <?php if ($Incident_Type == '3'){echo 'selected="selected"';} ?>>Persoon</option>
    <option value="4" <?php if ($Incident_Type == '4'){echo 'selected="selected"';} ?>>Technisch</option>
</select>
<br />
<select id="size" style="width: 100%" class="form-control">
    <?php
        if(empty($Incident_Type)){
            echo '<option value="" disabled="disabled">- Betreft -</option>';    
        }

        elseif($Incident_Type == '1'){
            $Subcategories_Select = mysqli_query($con, "SELECT * FROM `incidents_subcategories` WHERE `Categorie` = '$Incident_Type' ORDER BY `Name` ASC");
            ?>
<option value="" disabled="disabled" selected="selected">- Betreft -</option><?php
            while($row = $Subcategories_Select->fetch_assoc()) {
                ?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['Name']; ?></option><?php
            }
        }

    ?>

</select>


Nu zou ik graag de code welke ik gebruik om de subcategorieën in de tweede categorie (en dus uit mijn SQL-database haal) ook in mijn javascript-code terug willen laten komen. Waar nu dus staat:
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
$("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");

zou ik dus ook graag mijn sol-opties plaatsen.

P.s: Mijn eerste SQL gebruik ik enkel om "initieel" de select-options te laden.

De bron van mijn code komt van https://stackoverflow.com/a/4480674/9784688.

Alvast bedankt!
 
PHP hulp

PHP hulp

19/03/2024 08:28:17
 
Adoptive Solution

Adoptive Solution

19/03/2019 18:52:27
Quote Anchor link
Dit lijkt erop :

http://adoptive.2kool4u.net/dynamic_select/

De JavaScript code staat in de bron. De link naar Codexworld legt uit hoe het wordt gedaan.
 
Tim Klein

Tim Klein

19/03/2019 18:57:40
Quote Anchor link
Hoi Adoptive Solution, dank voor je antwoord!

Echter: wat ik zie is dat deze om en nabij dezelfde code gebruiken om de
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
$("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");

toe te passen. Dit is net niet waar ik naar opzoek ben: ik ben eigenlijk opzoek naar het stukje waardoor ik
<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option> kan vervangen door mijn SQL-script.

Tim
 
Adoptive Solution

Adoptive Solution

19/03/2019 19:11:04
Quote Anchor link
Dus je hebt in 5 minuten vastgesteld dat de gegeven oplossing niet is wat je wilt?
 
Thomas van den Heuvel

Thomas van den Heuvel

19/03/2019 19:16:19
Quote Anchor link
Wat is er op tegen om op voorhand alle subcategorie-menu's te bouwen en (verborgen) toe te voegen aan het HTML-document en dan, wanneer je een hoofdcategorie selecteert de bijbehorende dropdown voor subcategorieën te tonen?

Je zou het ook in JavaScript kunnen hardcoden zoals met dat if-elseif-elseif statement maar dat is toch een beetje een rare spagaat (en ook als je die informatie dynamisch uit de database wilt trekken zul je een mix moeten hebben van JavaScript, PHP en SQL), het is niet echt de juiste plaats (noch het juiste formaat) om de data te stallen denk ik.

Of je doet dus zoiets als @Adoptive voorstelt: je haalt op verzoek JSON / HTML op.
 
Tim Klein

Tim Klein

19/03/2019 21:45:53
Quote Anchor link
Goedenavond allemaal!

Dank voor jullie reacties. @Adaptive: ik was eigenlijk op zoek naar een SQL/PHP-optie in Javascript. Aangezien ik hier vrij nieuw/blanco in ben, wist ik oprecht niet of dit mogelijk was.

Daarnaast ben ik ook vrij nieuw in PHP. Ik heb op dit moment de volgende code:

index.php
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<script type="text/javascript">
$(document).ready(function(){
    $('#country').on('change',function(){
        var countryID = $(this).val();
        if(countryID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'country_id='+countryID,
                success:function(html){
                    $('#state').html(html);
                    $('#city').html('<option value="">Select state first</option>');
                }
            });
        }else{
            $('#state').html('<option value="">Select country first</option>');
            $('#city').html('<option value="">Select state first</option>');
        }
    });
    
    $('#state').on('change',function(){
        var stateID = $(this).val();
        if(stateID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'state_id='+stateID,
                success:function(html){
                    $('#city').html(html);
                }
            });
        }else{
            $('#city').html('<option value="">Select state first</option>');
        }
    });
});
</script>
<!-- w3-content defines a container for fixed size centered content,
and is wrapped around the whole page content, except for the footer in this example -->
<div class="w3-content" style="max-width:1600px">

      <?php
    //Include database configuration file
    include('dbConfig.php');
    
    //Get all country data
    $query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
    
    //Count total number of rows
    $rowCount = $query->num_rows;
    ?>

    <input type="hidden" name="Hidden" id="Hidden" value="">
    <select name="country" id="country" >
        <option value="">Select Country</option>
        <?php
        if($rowCount > 0){
            while($row = $query->fetch_assoc()){
                echo '<option value="'.$row['country_id'].'"'.(($row['country_id']=='224')?'selected="selected"':"").'>'.$row['country_name'].'</option>';
            }
        }
else{
            echo '<option value="">Country not available</option>';
        }

        ?>

    </select>
    
    <select name="state" id="state">
        <option value="">Select country first</option>
    </select>
    
    <select name="city" id="city">
        <option value="">Select state first</option>
    </select>
    </div>

          
            
      </div>
      
    </div>

  </div>

</div>

</body>
</html>
.

En op de ajaxData.php:
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
//Include database configuration file
include('dbConfig.php');

if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
    //Get all state data
    $query = $db->query("SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
    
    //Count total number of rows
    $rowCount = $query->num_rows;
    
    //Display states list
    if($rowCount > 0){
        echo '<option value="">Select state</option>';
        while($row = $query->fetch_assoc()){
            echo '<option value="'.$row['state_id'].'"'.(($row['state_id']=='2')?'selected="selected"':"").'>'.$row['state_name'].'</option>';
        }
    }
else{
        echo '<option value="">State not available</option>';
    }
}


if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
    //Get all city data
    $query = $db->query("SELECT * FROM cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
    
    //Count total number of rows
    $rowCount = $query->num_rows;
    
    //Display cities list
    if($rowCount > 0){
        echo '<option value="">Select city</option>';
        while($row = $query->fetch_assoc()){
            echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
        }
    }
else{
        echo '<option value="">City not available</option>';
    }
}

?>


Dit werk allemaal prima, tot hier kom ik er uit!

Nu wil ik alleen "initieël" de staten selecteren. Dit bijvoorbeeld omdat ik deze country_id uit een andere SQL-tabel haal. Hoe is dit mogelijk?

Ik heb zelf al geprobeerd om
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
echo '<option value="'.$row['state_id'].'"'.(($row['state_id']=='2')?'selected="selected"':"").'>'.$row['state_name'].'</option>';

te gebruiken, echter geeft dit wel een selected; het lijkt alleen niet of het value ook wordt meegenomen. Ik denk zelf aan een hidden value, ik weet alleen niet hoe deze hierin toe te passen.

Alvast bedankt!

P.s. Mijn resultaat is te vinden op http://wrbloods.000webhostapp.com/strand/test
Gewijzigd op 19/03/2019 21:53:03 door Tim Klein
 
Adoptive Solution

Adoptive Solution

19/03/2019 22:36:42
Quote Anchor link
Plak deze code aan het eind van het Javascript. Voor de duidelijkheid heb ik </script> toegevoegd.

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
    $.ajax({
        type:'POST',
        url:'ajaxData.php',
        data:'country_id=224',
        success:function(html){
            $('#state').html(html);
            $('#city').html('<option value="">Select state first</option>');
        }
    });

});
</script>


Als VS bij het open van de pagina wordt geselecteerd, worden nu de Staten in het tweede menu geladen.
 



Overzicht Reageren

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.