0

Okay so I'm having that JS :

 <script>
    $('#building').change(function () {
        var selectedValue = $(this).val();
        $.ajax({
            url: 'getunits.php',
            type: "POST",
            async:false,
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            data:{
                building: selectedValue,
            },

            success: function (result) {

                var e = document.getElementById('div1');
                e.innerHTML = result;
                eval(document.getElementById('runscript').innerHTML);

            }
        });
    });
</script>

<div id="div1">
</div>

And that in the PHP :

$selectunits = mysqli_query($con,"SELECT * FROM `units` WHERE `building`='".$building."'");
echo '<script type="text/javascript" id="runscript">';
while($rowunits = mysqli_fetch_assoc($selectunits))
{
    //echo '<option value="'.$rowunits["ID"].'">'.$rowunits["unit_number"].'</option>';
    echo '$("#unit").append("<option value="'.$rowunits["ID"].'">'.$rowunits["unit_number"].'</option>");';
}
echo'</\script>';

All I'm trying to do is after I select from the first select, an Ajax goes to that URL and fills up the 2nd select with different data. So what I was able to do is do a loop in the PHP to create the required JS to fill up.

Chris Bier
  • 14,183
  • 17
  • 67
  • 103
  • 3
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Aug 02 '17 at 14:04
  • I can only suspect, that your code does not work, because the browser already built the DOM and does not reparse the added – Daniel Christiany Aug 02 '17 at 14:20
  • Daniel may you please show me example, I never tried json data,\ – Moemen Waleed Aug 02 '17 at 14:38
  • and Alex, I already have mysqli_real_escape_string to the $_POST variable – Moemen Waleed Aug 02 '17 at 14:38
  • You should filter your result, but not document for "runscript" id. One of the solutions is - use json response type if possible. – Anton Aug 02 '17 at 14:52
  • This is not the right way to pass data to the page. All you need is to echo JSON (using `json_encode()`), which can be parsed by your AJAX success/done callback. – Terry Aug 02 '17 at 16:06

0 Answers0