1

Hi guys I want to append a div but it has some javascript/ajax calls so how do I append it in the way that the javascript codes will work in the appended div? at the moment i have 3 dropdowns, category > subcategory and question. How the calls work, when a category is selected, subcategoryies will display in the second dropdown under that category and when a subcategory is selected, questions will be displayed in the third dropdown under that subcategory. I want that to work also in the appended divs. How do i do it? because currently its just duplicating my div with my current append code.

new1.php

    <?php
        $con = mysqli_connect("localhost","root","","imetrics") or die ("Cannot connect to the database!");

        ?>

            <form name="form1" action="" method="post">

                <div id="sform" class="tab-pane fade">

               <br>

               <div class="col-md-12">
                   <div class="col-md-10" id="sections">
                       <div class="panel-group">
                           <div class="panel panel-default">
                               <div class="panel-heading">Section 1</div>
                               <div class="panel-body">


                                   <b>Number of Questions: </b>


                                   <span id="ctr_num"> <input id="q_num" class="form-control" style="width:50px;" name="q_num" size="2" placeholder="#"/></span>
                                   <br/>


                                   <b>Select Category</b>


                                   <select class="form-control" style="width: 150px;" id="categorydd" name="catdd" onChange="change_category()">

                                       <option>-Please Select One-</option>

                                       <?php
                                       $query=mysqli_query($con, "SELECT category_id, categoryname FROM category WHERE ParentCategoryID IS NULL");
                                       while($row=mysqli_fetch_array($query)) {
                                           ?>
                                           <option value="<?php echo $row["category_id"]; ?>"><?php echo $row["categoryname"]; ?></option>

                                           <?php
                                       }
                                       ?>

                                   </select>
                                   <br/>
                                   <b>Select Subcategory</b>

                                   <div id="subcategory">

                                       <select class="form-control" style="width: 150px;">

                                           <option>-Please Select One-</option>
                                       </select>
                                       <br/>
                                   </div>
                                   <p hidden>Select Questions</p>

                                   <br/>

                                   <div id="question">

                                   </div>      <br/>

                               </div>
                           </div>
                       </div>
                   </div>
               </div>
           </div>
           <hr>
       <div class="col-md-2">
       <input type="submit" name="addsection" class="btn btn-default" value="Add Section" id="addsection" />

       </div>





            </form>

<script type="text/javascript">
  function change_category()
{
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET","ajax.php?category="+document.getElementById("categorydd").value,false);
    xmlhttp.send(null);
    document.getElementById("subcategory").innerHTML=xmlhttp.responseText;


    if(document.getElementById("categorydd").value=="Select")
    {
    document.getElementById("question").innerHTML="<select><option>Select</option></select>";
    }

    //alert(document.getElementById("categorydd").value);
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET","ajax.php?main=1&subcategory="+document.getElementById("categorydd").value +"&cnt="+document.getElementById("q_num").value,false);
    xmlhttp.send(null);
    document.getElementById("question").innerHTML=xmlhttp.responseText;
}


function load_questions(){

    var xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
    xmlhttp.send(null);
    document.getElementById("question").innerHTML=xmlhttp.responseText;


}
    $(document).ready(function(){
        var ctr = 0;
        $("#addsection").click(function(){
            var section = document.getElementById("sections").innerHTML;
            $("#sections").append(section);


            ctr++;


        });

    });




</script>

new2.php

    <?php
    $con = mysqli_connect("localhost","root","","imetrics") or die ("Cannot connect to the database!");

    $category= isset($_GET["category"])?$_GET["category"]:"";
    $subcat=isset($_GET["subcategory"])?$_GET["subcategory"]:"";
    $question=isset($_GET["subcategory"])?$_GET["subcategory"]:"";

    if($category!=""){

    $query=mysqli_query($con, "SELECT category_id, categoryname FROM category WHERE ParentCategoryID =$category ");
    echo "<select id='subcategorydd' class='form-control' style='width:150px;' name='subcatdd' onchange='load_questions()' >";
    echo "<option selected>"; echo "Select"; echo "</option>";
    while($row=mysqli_fetch_array($query))
    {
        echo "<option value='$row[category_id]'>"; echo $row["categoryname"]; echo "</option>";
    }
    echo "</select>";
}

// for loading ques under Category already
if($question !="" && $cnt!="" && $addQues!="yes" && $main == 1){
    $i = 0;
    for( $i = 1; $i <= $cnt; $i++ ){
        $query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");


        echo "<form id='ques{$i}'>
        <b id='labelquestion_dropdown{$i}'>Question #{$i}</b>
        <select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
            <option selected>Select";

        while($row=mysqli_fetch_array($query)){
            echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
        }

        echo "
        </select>

    <div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
    <br /></form>";
    }
    echo "<div id='insertQuesHere".$i."'></div>";

    echo "<a href='#add_question' onclick='return addQues_Cat();'>Add Question</a> | ";
    echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}

// for loading ques under SUBCATEGORY
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
    $i = 0;
    for ($i = 1; $i <= $cnt; $i++)
    {
        $query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
        echo "
    <form id='ques{$i}'>
        <b id='labelquestion_dropdown{$i}'>Question #{$i}</b>
        <select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
     <option selected>Select";
        while($row=mysqli_fetch_array($query))
        {
            echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
        }

        echo "
        </select>

    <div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
    </form>  
    <br />";
    }

    echo "<div id='insertQuesHere".$i."'></div>     ";

    echo "<a href='#add_question' onclick='return addQues();'>Add Question</a> | ";
    echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}

    ?>
  • Can you provide a fiddle? – hallleron Jul 27 '17 at 08:04
  • Just bind the event again after the ajax call – Rudie Visser Jul 27 '17 at 08:04
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Jul 27 '17 at 08:28
  • @hallleron its all dynamic sir and i dont know how to upload db in fiddle. –  Jul 27 '17 at 08:43
  • Can you please show me a sample code sir @RudieVisser I've been stuck on this problem for too long :( –  Jul 27 '17 at 08:43
  • 1
    @McGregor I am aware of that, but you can provide sample data in a fiddle that represent the output of for example you database queries. If your query for example returns an array with strings like ["one", "two"] you could just simulate a similar response with variables. – hallleron Jul 27 '17 at 08:51
  • I have answered with a sample @McGregor – Rudie Visser Jul 27 '17 at 09:10

1 Answers1

0

After your ajax call

function change_category()
    {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET","new2.php?category="+document.getElementById("categorydd").value, false);
        xmlhttp.send(null);
        document.getElementById("subcategory").innerHTML = xmlhttp.responseText;

        if(document.getElementById("categorydd").value=="Select"){
            document.getElementById("question").innerHTML="<select><option>Select</option></select>";
        }
    }

Just bind the event again like here

    $(document).ready(function(){
        var ctr = 0;
        $("#addsection").click(function(){
            var section = document.getElementById("sections").innerHTML;
            $("#sections").append(section);


            ctr++;


        });

    });

Your change_category function becomes

function change_category()
    {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET","new2.php?category="+document.getElementById("categorydd").value, false);
        xmlhttp.send(null);
        document.getElementById("subcategory").innerHTML = xmlhttp.responseText;

        if(document.getElementById("categorydd").value=="Select"){
            document.getElementById("question").innerHTML="<select><option>Select</option></select>";
        }

        $("#addsection").click(function(){
            var section = document.getElementById("sections").innerHTML;
            $("#sections").append(section);
        });
    }
Rudie Visser
  • 570
  • 6
  • 23
  • Sir nothing is happening when i click on the add section button. I want it to append the div where the 3 dropdowns are in. –  Jul 27 '17 at 09:54
  • I guess I want it to have unique id so the dropdowns from each sections don't have conflicts with each other –  Jul 27 '17 at 09:57
  • I've updated the answer as I took the wrong ajax call, change your code according to the new answer and let me know if that works @McGregor – Rudie Visser Jul 27 '17 at 10:00
  • Still not working sir. But sir im sorry also because the code I pasted on my question earlier was the simpler version of the current code I have right now. But now I edited my post with the code I have now. But still the same problem. Please spare time to read my code again i edited it and hope you can still help me. –  Jul 27 '17 at 10:51
  • Btw I didn't include the other functions in my question because it's not related to my problem and to avoid confusion that's why I only included the change_category and load_questions since they are related to the 3 dropdowns. Please help me sir rudie –  Jul 27 '17 at 10:58