0

I've been trying to use AJAX and JSON to show the contents of individual items from my database through the following codes below. What I'm trying to achieve is that whenever an individual item is opened or clicked, it will show up its unique content on the next page.

However, succeeding items just show the details of the initial item which has the ID '1'. I have more than 10 items in my DB and I want these to reflect their corresponding data.

//productpage_endpoint.php

require "connection.php";

$id = $_POST['id'];
$sql = "SELECT * FROM items WHERE id = $id";
$result = mysqli_query($conn,$sql);
$result = mysqli_fetch_assoc($result);
echo json_encode($result);


<script type="text/javascript">
   $.post('productpage_endpoint.php',**{id: 1}**,
            function(data){
                var item = JSON.parse(data)
                $('input[name=name]').val(item.name)
                $('input[name=description]').val(item.description)
                $('input[name=price]').val(item.price)
                $('#item_image').attr('src',item.image)
            }
          ) 
</script>
mega6382
  • 9,211
  • 17
  • 48
  • 69
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – mega6382 Oct 15 '17 at 14:40

1 Answers1

0

If you'd like to request all items in the table:

$sql = "SELECT * FROM items";

In JS you'll need to create new elements for all of the values. Otherwise you'll overwrite the existing form values.

$.post('productpage_endpoint.php',
    function(data){
        for (var item in data) {
            $('<input>')
              .attr('name', 'name')
              .attr('type', 'text')
              .val(item.name);
            // ...
            // Add to your form...
        }
    }
)
Matt S
  • 14,976
  • 6
  • 57
  • 76
  • Thanks! I did the modification but is still the same. It still shows the data of item 1 (name,price,genre, etc.) whenever I click item 2,3,4 and so on. I tried making a loop in my script's part where it states $.post('productpage_endpoint.php',{id: 1}, because I have a total of 24 items but can't figure out how to get it right. – dovahkiin Oct 16 '17 at 02:08