-4

I have one json object and I want to fetch it by calling ajax

[  { "color":"black",   "productid":"1",    "price":"1000" },  {
    "color":"blue",     "productid":"2",    "price":"2000" },  {
    "color":"green",    "productid":"3",    "price":"3000" },  {
    "color":"grey",     "productid":"4",    "price":"4000" },  {
    "color":"orange",   "productid":"5",    "price":"5000" },  {
    "color":"purple",   "productid":"6",    "price":"6000" },  {
    "color":"red",      "productid":"7",    "price":"7000" },  {
    "color":"violet",   "productid":"8",    "price":"8000" },  {
    "color":"white",    "productid":"9",    "price":"9000" },  {
    "color":"yellow",   "productid":"10",   "price":"10000" },  ]

This is the json file and I wrote ajax as below.

$.ajax({url: 'products.json',          
       dataType: 'json',         
       data: 'data',         
       success: function(data, status, xhr) {             
                                 alert(data);         
                },        
                error: function(xhr, status, error) {              
                                  alert(status);        
              } 
       });
Carl Binalla
  • 5,393
  • 5
  • 27
  • 46
  • Possible duplicate of [how to parse json data with jquery / javascript?](https://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript) – Amar Singh Jun 29 '17 at 06:31

1 Answers1

1

Here is the right code for fetching JSON from products.json and also your json is not valid syntax error

 $.ajax({
  url: 'products.json',
  dataType: 'json',
  success: function(data, status, xhr) {
   alert(data);
  },
  error: function(xhr, status, error) {
   alert(status);
  }
 });

Product JSON Should be

 [{
     "color": "black",
     "productid": "1",
     "price": "1000"
 }, {
     "color": "blue",
     "productid": "2",
     "price": "2000"
 }, {
     "color": "green",
     "productid": "3",
     "price": "3000"
 }, {
     "color": "grey",
     "productid": "4",
     "price": "4000"
 }, {
     "color": "orange",
     "productid": "5",
     "price": "5000"
 }, {
     "color": "purple",
     "productid": "6",
     "price": "6000"
 }, {
     "color": "red",
     "productid": "7",
     "price": "7000"
 }, {
     "color": "violet",
     "productid": "8",
     "price": "8000"
 }, {
     "color": "white",
     "productid": "9",
     "price": "9000"
 }, {
     "color": "yellow",
     "productid": "10",
     "price": "10000"
 } ]
Umashankar
  • 694
  • 7
  • 21