1

I'm having a little trouble configuring a live preview of data via AJAX. I managed to get a preview with the following code but I'm a bit stuck in how to proceed. My next step is displaying the image url provided from the same table. As I am fairly new to PHP and AJAX (especially) I'm not getting any further with this code. This is how the HTML looks like:

PHP logic:

$query = $conn->prepare("SELECT * FROM items WHERE user_id = $userID");
$query->execute();

The HTML Form:

<div class="form-group">
<div id="results"></div>

<form action="" method="post">
  <label for="sel1">Selecteer uw items:</label>

  <select class="form-control" id="sel1"multiple>

    <?php
        while ($q = $query->fetch()){
          echo '<option value="' . $q['id'] . '">' . $q['Beschrijving'] 
          . '</option>';
        }
    ?>

  </select>

  <button type="button" class="btn btn-success" name="submit">Toevoegen 
   aan board</button>
 </form>

 </div>

The Ajax/JS script:

<script type="text/javascript">
$("#sel1").on("change", function(){
function clearpost(){
  $("#results").val("");
}

var selected = $(this).val();
makeAjaxRequest(selected);
function makeAjaxRequest(opts){
  $.ajax({
    type:"POST",
    data:{opts: opts},
    url:"views/itemOverview.php",
    success:function(res){
      $("#results").html("<p>Uw items : " + res + "</p>");
    }
  })
}

})
</script>

The PHP file:

echo '<pre>';
print_r($_POST);
echo '</pre>';

This is the result:

Multiple Selections from list

All feedback is much appreciated! Kind regards

Moya
  • 89
  • 1
  • 2
  • 10

1 Answers1

1

In your case the PHP file should return json object that you can use in ajax success callback. Please refer Returning JSON from a PHP Script from returning json from server. in case of object sample code goes like,

$res = new stdClass();
$res->name = "sample"; // from db
$res->imageUrl = "img/img1.png";// from db
echo json_encode($res);

In your js file you can do something like,

$.ajax({
    type:"POST",
    data:{opts: opts},
    url:"views/itemOverview.php",
    datatype: "text/json", // this is preferred when receiving json data
    success:function(res){
      // res is json object. res.name & res.imageUrl are it's property
      $("#results").html("<p>Uw items : " + res.name + " <img src='"+ res.imageUrl+"' /></p>");
    }
  })
Community
  • 1
  • 1