AJAX, PHP, and Javascript to populate a form input

2019-08-28 00:58发布

问题:

Im way out of my knowledge on this one, so i thought i could need some help...

Background:

I have a form which needs to have dynamic drop down lists, based on a postcode(text box) this was done by AJAX function which called a PHP file like below

....

<select name="choice1" id="choice1">
    <?php
         //Block of code to populate drop down menu from a SQL command
    ?>
</select>

....

The functionality works, as it displays on change of postcode, and becomes populated. My issue is that i have noticed its not apart of the form or i cannot use JS.. with this device as now i need to take a value from the drop down menu into another textbox.

is it possible to add this into the form? or even atleast use JS so i can get the value?

Thankyou..

EDIT

This is my function which calls the PHP file:

function choiceDropdowns(code){
        var postcode = code.value;
        var xmlhttp;

        if (window.XMLHttpRequest){
            xmlhttp=new XMLHttpRequest();
        }
        else{
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                document.getElementById("div4").innerHTML=xmlhttp.responseText;
            }
        }

        xmlhttp.open("GET","createChoice123DropDown.php?postcode="+postcode,true);
        xmlhttp.send();
    }

PHP file:

<body>
    <select name="choice1" id="choice1">
    <?php
        $postcode = $_GET["postcode"];

        $conn = mysql_connect("localhost", "XXXX", "XXXX");
        mysql_select_db(XXXX, $conn)
        or die('Database not found ' . mysql_error());

        $sql = "SELECT school_info.Name, school_info.schoolID FROM school_info INNER JOIN local_schools ON school_info.schoolID = local_schools.schoolID INNER JOIN valid_postcodes ON local_schools.postcodeID=valid_postcodes.id WHERE valid_postcodes.postcode != '$postcode' AND school_info.school_type ='S'";
        $rs = mysql_query($sql, $conn)
        or die ('Problem with query' . mysql_error());

        while($row = mysql_fetch_array($rs)){
            echo '<option value="'.$row["schoolID"].'">'.$row["Name"].'</option>';
        }
    ?>
    </select>
</body>

This is my form (cut down in size obviously):

<form method="get" id="eoi_form" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
    <td>Choice 1:<div id="div4"></div></td>
</form>

回答1:

You doing it wrong =) Why don't you return all your options with json, and after that just append it to your select box:

var select = $('#my_select')
$.post('update_options', function(response) {
    $.each(response.options, function(i, item) {
        var option = $('<option>');
        if (item.value) option.attr('value', item.value);
        option.text(item.text);
        select.append(option);
    });
});