0

I'm trying to create a JavaScript object based on a template I received as a test. I use Ajax to get the data from my database but i cant seem to create the object.

$(document).ready(function() {
  $.ajax({
    type: 'POST',
    url: 'fetch.php',
    dataType: 'JSON',
    success: function(response) {
      var test = JSON.parse(response);
      var products = {};
      for (var x = 0; x < test.length; x++) {
        products[x] = {
          productName: test[x]['name']
        };
        products[x] = {
          category: test[x]['category']
        };
        products[x] = {
          price: test[x]['price']
        };
      }
    }
  });
});

I'm trying to create something like this object below

products = {data: [
{
  productName: "test_item_1",
  category: "category1",
  price: "49",
  image: "test_image.jpg",
},
{
  productName: "test_item_2",
  category: "category3",
  price: "99",
  image: "test_image.jpg",
},
{
  productName: "test_item_3",
  category: "category3",
  price: "29",
  image: "test_image.jpg",
},],};

This is the how i fetch the data from my database

while($row = mysqli_fetch_assoc($run)){$datas[] = $row;}echo json_encode($datas);
5
  • why don't you create that object from fetch.php? Commented Mar 6, 2022 at 23:00
  • 1
    Please post the JSON. Commented Mar 6, 2022 at 23:03
  • In your second codeblock, products is not properly encoded. Commented Mar 6, 2022 at 23:04
  • In PHP you can use function json_encode Commented Mar 6, 2022 at 23:04
  • Why are you POST-ing with no data? Commented Mar 6, 2022 at 23:12

2 Answers 2

1

Your lines with products[x] overwrite the earlier.

Change to

                  products[x] = {
                      productName: test[x]['name'],
                      category: test[x]['category'],
                      price: test[x]['price'],
                  };
Sign up to request clarification or add additional context in comments.

Comments

1

There's a couple of problems first...

  1. The $.ajax() config option is dataType, not datatype
  2. Specifying dataType: "json" means jQuery will automatically parse the response as JSON. You don't need to manually parse it again

As to your mapping problem, you can map the response array to a new one with name renamed to productName using Array.prototype.map()

$.ajax("fetch.php", {
  method: "POST",
  dataType: "json",
  // data: ¯\_(ツ)_/¯
}).done(data => {
  const products = {
    data: data.map(({ name: productName, category, price }) => ({
      productName,
      category,
      price
    }))
  };
});

Comments

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.