0

I attempt to fill a drop down from a database. I query and add my result to an array. I then use json_encode to send my data to a php file.

$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
       $proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
       $pselected=$row_id['project'];
}
$output = array( "proj" => $proj_option);
echo json_encode($output);

In my php file, I use jquery ajax to fill the drop down.

$("#turninId").change(function() {

    var user_id = $("#turninId").val();

    $.ajax ( {
      url:"send_input.php",
      type: "POST",
      dataType: "json",
      data:{id_selection: user_id},
      success:function(response) {

        for (var i=0; i<response.proj.length; i++) {
          $("#exp").html(response.proj[i]);
          $("#project").html(response.proj[i]); } });

 });

This is great, BUT the only item in my drop down is the last item in the db. For example, my database has the following under Project:

Project: up, down, low, right

But my drop down only fills with the last entry, "right." Why is this? How can I fix it?

PHP json_encode() in while loop was similar, and I made the changes, but there is something missing here.

2 Answers 2

1

may be try this

success:function(response) {

  $.each(response.proj,function(key,value){
      $("#exp").append(value);
      $("#project").append(value);
  });

}
0
0

each time thru your loop in javascript you are overwriting your html. The .html() method sets the innerHTML property of the tag, so each time you call it you are resetting the html and only the last one will show. try not using a loop, instead join you response together and then call .html()

$("#exp").html(response.proj.join(''));
$("#project").html(response.proj.join(''));
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.