We help IT Professionals succeed at work.

Json and ajax javascript

Moti Mashiah
Moti Mashiah asked
on
174 Views
Last Modified: 2017-05-14
Hi Guys,

I'm trying to read json list object through ajax:
Here is my json data return - which basically return 2 rows:
[{"BinLocation":"16A","BuydownPrice":0.0000,"BuydownQuantity":0.0,"CommissionAmount":0.0000,"CommissionMaximum":0.0000,"CommissionMode":0,"CommissionPercentProfit":0.0,"CommissionPercentSale":0.0,"Description":"3  B/G H.D. MYLAR  K","FoodStampable":false,"HQID":139858,"ItemNotDiscountable":false,"LastReceived":"2007-06-07T00:00:00","LastUpdated":"2013-01-18T16:24:06","Notes":null,"QuantityCommitted":0.0,"SerialNumberCount":0,"TareWeightPercent":0.0,"ID":1,"ItemLookupCode":"0839420-EA","DepartmentID":8,"CategoryID":614,"MessageID":0,"Price":0.7900,"PriceA":0.0000,"PriceB":0.0000,"PriceC":0.0000,"SalePrice":0.0000,"SaleStartDate":null,"SaleEndDate":null,"QuantityDiscountID":0,"TaxID":1,"ItemType":0,"Cost":0.2282,"Quantity":27.0,"ReorderPoint":0.0,"RestockLevel":0.0,"TareWeight":0.0,"SupplierID":316,"TagAlongItem":0,"TagAlongQuantity":0.0,"ParentItem":0,"ParentQuantity":6.0,"BarcodeFormat":7,"PriceLowerBound":0.0000,"PriceUpperBound":0.0000,"PictureName":"","LastSold":"2012-12-04T00:00:00","ExtendedDescription":"","SubDescription1":"THE HILLMAN GROUP","SubDescription2":"0823646951","SubDescription3":"","UnitOfMeasure":"EA","SubCategoryID":0,"QuantityEntryNotAllowed":false,"PriceMustBeEntered":true,"BlockSalesReason":"","BlockSalesAfterDate":null,"Weight":0.0,"Taxable":true,"DBTimeStamp":"AAAAAON/fP0=","BlockSalesBeforeDate":null,"LastCost":0.0000,"ReplacementCost":0.0000,"WebItem":false,"BlockSalesType":0,"BlockSalesScheduleID":0,"SaleType":0,"SaleScheduleID":0,"Consignment":false,"Inactive":false,"LastCounted":"2007-08-25T00:00:00","DoNotOrder":false,"MSRP":0.0000,"DateCreated":"2001-02-26T00:00:00","Content":"","UsuallyShip":"","NumberFormat":null,"ItemCannotBeRet":null,"ItemCannotBeSold":null,"IsAutogenerated":null,"IsGlobalvoucher":false,"DeleteZeroBalanceEntry":null,"TenderID":0},{"BinLocation":"16A","BuydownPrice":0.0000,"BuydownQuantity":0.0,"CommissionAmount":0.0000,"CommissionMaximum":0.0000,"CommissionMode":0,"CommissionPercentProfit":0.0,"CommissionPercentSale":0.0,"Description":"3  B/G H.D. MYLAR  P","FoodStampable":false,"HQID":139861,"ItemNotDiscountable":false,"LastReceived":"2007-06-07T00:00:00","LastUpdated":"2013-01-18T16:24:06","Notes":null,"QuantityCommitted":0.0,"SerialNumberCount":0,"TareWeightPercent":0.0,"ID":4,"ItemLookupCode":"0839430-EA","DepartmentID":8,"CategoryID":614,"MessageID":0,"Price":0.8900,"PriceA":0.0000,"PriceB":0.0000,"PriceC":0.0000,"SalePrice":0.0000,"SaleStartDate":null,"SaleEndDate":null,"QuantityDiscountID":0,"TaxID":1,"ItemType":0,"Cost":0.2282,"Quantity":17.0,"ReorderPoint":0.0,"RestockLevel":0.0,"TareWeight":0.0,"SupplierID":316,"TagAlongItem":0,"TagAlongQuantity":0.0,"ParentItem":0,"ParentQuantity":6.0,"BarcodeFormat":7,"PriceLowerBound":0.0000,"PriceUpperBound":0.0000,"PictureName":"","LastSold":"2010-05-18T00:00:00","ExtendedDescription":"","SubDescription1":"THE HILLMAN GROUP","SubDescription2":"0823646956","SubDescription3":"","UnitOfMeasure":"EA","SubCategoryID":0,"QuantityEntryNotAllowed":false,"PriceMustBeEntered":false,"BlockSalesReason":"","BlockSalesAfterDate":null,"Weight":0.0,"Taxable":true,"DBTimeStamp":"AAAAAOJyynU=","BlockSalesBeforeDate":null,"LastCost":0.0000,"ReplacementCost":0.0000,"WebItem":false,"BlockSalesType":0,"BlockSalesScheduleID":0,"SaleType":0,"SaleScheduleID":0,"Consignment":false,"Inactive":false,"LastCounted":"2007-08-25T00:00:00","DoNotOrder":false,"MSRP":0.0000,"DateCreated":"2001-02-26T00:00:00","Content":"","UsuallyShip":"","NumberFormat":null,"ItemCannotBeRet":null,"ItemCannotBeSold":null,"IsAutogenerated":null,"IsGlobalvoucher":false,"DeleteZeroBalanceEntry":null,"TenderID":0}]

Open in new window


Here is the ajax call when I get the date and try to inject it to the table:
function TestApi(){
              $.ajax({
                type: "GET",
                url: 'http://localhost:49175/api/items',
                dataType: "html",
                //data: { },
                success: function (data) {
                    console.log(data)
                    $("#idt tbody tr").each(function (){
                        $(this).html("<td>'" + data.Description + "'</td><td>'"+ data.Description +"'</td><td>'"+ data.Price +"'</td>")
                    });
                }
            });
}

Open in new window


I'm getting the "data" and can see the two rows, but when I loop through I'm getting undefined.
Please help.
Comment
Watch Question

HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
I'm getting the "data" and can see the two rows

what do you see in data?
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
$(this).html("<td>'" + data.Description + "'</td><td>'"+ data.Description +"'</td><td>'"+ data.Price +"'</td>")
>>>
$(this).html("<td>" + data.Description + "</td><td>"+ data.Description +"</td><td>"+ data.Price +"</td>")

you dont need ', also why do you use data.Description twice?
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
success: function (data) {
                    console.log(data)
                    $("#idt tbody tr").each(function (){
                        $(this).html("<td>'" + data.Description + "'</td><td>'"+ data.Description +"'</td><td>'"+ data.Price +"'</td>")
                    });
                }

Open in new window


here you are looping rows in idt table, and assigning same data!
are you sure you want to do this?
does not make sense to me...
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
maybe you should do this

success: function (data) {
  //console.log(data)
  // ??? loop elements in your data, {
  $('#idt > tbody:last-child').append("<td>'" + data.Description + "'</td><td>'"+ data.Price +"'</td>");
  // }
  });
}

Open in new window

Moti Mashiah.NET Developer

Author

Commented:
Hi and thank you for your answer.

Actually to make more sense I will share my dom.
 <table border=1 id="idt">
       <thead>
       <tr>
           <th>Itemlookupcode</th>
           <th>Description</th>
           <th>Price</th>
       </tr>
       </thead>
       <tbody>
           <tr>

           </tr>
       </tbody>
   </table>

Open in new window


so in order to select the right row i do.
 $("#idt tbody tr").each(function (){
$(this).html("<td>'" + data.Description + "'</td><td>'"+ data.Description +"'</td><td>'"+ data.Price +"'</td>")
})

This working and all good. the only issue I have is that I'm getting the data as undefined.
Let's say "data.Description" comes undefined although when I query the "data" I'm getting all data.

so my question is how do I get the properties from the "data" variable.

Thanks.
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
your code loops your table not data!

also, still, why do you repeat data.Description twice?
Itemlookupcode / Description are same?
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
and your table has only one tr, why you are looping?

what are you trying to do here?

what is data look like?
do you want to loop data and add them into your table? if yes, I gave you the code, but not sure how your data is, thats why I did not add code there

again
success: function (data) {
  //console.log(data)
  // ??? loop elements in your data, {
  $('#idt > tbody:last-child').append("<tr><td>'" + data.Description + "'</td><td>'"+ data.Price +"'</td></tr>");
  // }
  });
}

Open in new window

Moti Mashiah.NET Developer

Author

Commented:
sorry, I just debugged and did changes and didn't pay attention to the description duplication.
this is basically my code:
$(this).html("<td>'" + data.Itemlookupcode  + "'</td><td>'"+ data.Description +"'</td><td>'"+ data.Price +"'</td>")
Moti Mashiah.NET Developer

Author

Commented:
But still I don't get the data.
Moti Mashiah.NET Developer

Author

Commented:
data variable gives all the rows but still when I do - data.Description I don't get the specific data.
Moti Mashiah.NET Developer

Author

Commented:
I don't get any property. its all come undefined , the weird things here is when the data variable gives the json back just fine, but again when you add the property you get undefined.

thank,
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
I keep asking the same thing...

what is your data look like
what are you trying to do when you get the data
your code loops all rows in your table, which is 1, and populates it with data or crashes here since you need to loop data items...

so, if you give answers to these you should do this

success: function (data) {
  //console.log(data)
  // ??? loop elements in your data, {
  $('#idt > tbody:last-child').append("<tr><td>'" + data.Itemlookupcode + "'</td><td>'" + data.Description + "'</td><td>'"+ data.Price +"'</td></tr>");
  // }
  });
}

Open in new window

HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
ok, got it
use this

this.BinLocation
success: function (data) {
  $(data).each(function (){
$('#idt > tbody:last-child').append("<tr><td>'" + this.Itemlookupcode + "'</td><td>'" + this.Description + "'</td><td>'"+ this.Price +"'</td></tr>");
  });
}

Open in new window

Moti Mashiah.NET Developer

Author

Commented:
Here is my data return:
json
[{"BinLocation":"16A","BuydownPrice":0.0000,"BuydownQuantity":0.0,"CommissionAmount":0.0000,"CommissionMaximum":0.0000,"CommissionMode":0,"CommissionPercentProfit":0.0,"CommissionPercentSale":0.0,"Description":"3  B/G H.D. MYLAR  K","FoodStampable":false,"HQID":139858,"ItemNotDiscountable":false,"LastReceived":"2007-06-07T00:00:00","LastUpdated":"2013-01-18T16:24:06","Notes":null,"QuantityCommitted":0.0,"SerialNumberCount":0,"TareWeightPercent":0.0,"ID":1,"ItemLookupCode":"0839420-EA","DepartmentID":8,"CategoryID":614,"MessageID":0,"Price":0.7900,"PriceA":0.0000,"PriceB":0.0000,"PriceC":0.0000,"SalePrice":0.0000,"SaleStartDate":null,"SaleEndDate":null,"QuantityDiscountID":0,"TaxID":1,"ItemType":0,"Cost":0.2282,"Quantity":27.0,"ReorderPoint":0.0,"RestockLevel":0.0,"TareWeight":0.0,"SupplierID":316,"TagAlongItem":0,"TagAlongQuantity":0.0,"ParentItem":0,"ParentQuantity":6.0,"BarcodeFormat":7,"PriceLowerBound":0.0000,"PriceUpperBound":0.0000,"PictureName":"","LastSold":"2012-12-04T00:00:00","ExtendedDescription":"","SubDescription1":"THE HILLMAN GROUP","SubDescription2":"0823646951","SubDescription3":"","UnitOfMeasure":"EA","SubCategoryID":0,"QuantityEntryNotAllowed":false,"PriceMustBeEntered":true,"BlockSalesReason":"","BlockSalesAfterDate":null,"Weight":0.0,"Taxable":true,"DBTimeStamp":"AAAAAON/fP0=","BlockSalesBeforeDate":null,"LastCost":0.0000,"ReplacementCost":0.0000,"WebItem":false,"BlockSalesType":0,"BlockSalesScheduleID":0,"SaleType":0,"SaleScheduleID":0,"Consignment":false,"Inactive":false,"LastCounted":"2007-08-25T00:00:00","DoNotOrder":false,"MSRP":0.0000,"DateCreated":"2001-02-26T00:00:00","Content":"","UsuallyShip":"","NumberFormat":null,"ItemCannotBeRet":null,"ItemCannotBeSold":null,"IsAutogenerated":null,"IsGlobalvoucher":false,"DeleteZeroBalanceEntry":null,"TenderID":0},{"BinLocation":"16A","BuydownPrice":0.0000,"BuydownQuantity":0.0,"CommissionAmount":0.0000,"CommissionMaximum":0.0000,"CommissionMode":0,"CommissionPercentProfit":0.0,"CommissionPercentSale":0.0,"Description":"3  B/G H.D. MYLAR  P","FoodStampable":false,"HQID":139861,"ItemNotDiscountable":false,"LastReceived":"2007-06-07T00:00:00","LastUpdated":"2013-01-18T16:24:06","Notes":null,"QuantityCommitted":0.0,"SerialNumberCount":0,"TareWeightPercent":0.0,"ID":4,"ItemLookupCode":"0839430-EA","DepartmentID":8,"CategoryID":614,"MessageID":0,"Price":0.8900,"PriceA":0.0000,"PriceB":0.0000,"PriceC":0.0000,"SalePrice":0.0000,"SaleStartDate":null,"SaleEndDate":null,"QuantityDiscountID":0,"TaxID":1,"ItemType":0,"Cost":0.2282,"Quantity":17.0,"ReorderPoint":0.0,"RestockLevel":0.0,"TareWeight":0.0,"SupplierID":316,"TagAlongItem":0,"TagAlongQuantity":0.0,"ParentItem":0,"ParentQuantity":6.0,"BarcodeFormat":7,"PriceLowerBound":0.0000,"PriceUpperBound":0.0000,"PictureName":"","LastSold":"2010-05-18T00:00:00","ExtendedDescription":"","SubDescription1":"THE HILLMAN GROUP","SubDescription2":"0823646956","SubDescription3":"","UnitOfMeasure":"EA","SubCategoryID":0,"QuantityEntryNotAllowed":false,"PriceMustBeEntered":false,"BlockSalesReason":"","BlockSalesAfterDate":null,"Weight":0.0,"Taxable":true,"DBTimeStamp":"AAAAAOJyynU=","BlockSalesBeforeDate":null,"LastCost":0.0000,"ReplacementCost":0.0000,"WebItem":false,"BlockSalesType":0,"BlockSalesScheduleID":0,"SaleType":0,"SaleScheduleID":0,"Consignment":false,"Inactive":false,"LastCounted":"2007-08-25T00:00:00","DoNotOrder":false,"MSRP":0.0000,"DateCreated":"2001-02-26T00:00:00","Content":"","UsuallyShip":"","NumberFormat":null,"ItemCannotBeRet":null,"ItemCannotBeSold":null,"IsAutogenerated":null,"IsGlobalvoucher":false,"DeleteZeroBalanceEntry":null,"TenderID":0}]

Open in new window

HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
I know... above code should add 2 rows to your table, but remove trs from your table

see this
https://jsfiddle.net/carm5n02/

I used

html
<table border=1 id="idt">
  <thead>
    <tr>
      <th>Itemlookupcode</th>
      <th>Description</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Open in new window


code
$(data).each(function() {
  $('#idt > tbody:last-child').append("<tr><td>" + this.BinLocation + "</td><td>" + this.Description + "</td><td>" + this.Price + "</td></tr>");
});

Open in new window

Moti Mashiah.NET Developer

Author

Commented:
I see its working for you in the code you sent me and I feel really stupid :) to miss the data into the each method.

Anyways, I'm getting error now.

Here is my code (exactly like you did):
function TestApi(){
              $.ajax({
                type: "GET",
                url: 'http://localhost:49175/api/items',
                dataType: "html",
                success: function (data) {
                    $(data).each(function() {
                      $('#idt > tbody:last-child').append("<tr><td>" + this.BinLocation + "</td><td>" + this.Description + "</td><td>" + this.Price + "</td></tr>");
                        });
                       }
                      });
                 }

Open in new window

Moti Mashiah.NET Developer

Author

Commented:
Im getting syntax error here and I don't get why?

jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: [{"BinLocation":"16A","BuydownPrice":0.0000,"BuydownQuantity":0.0,"CommissionAmount":0.0000,"CommissionMaximum":0.0000,"CommissionMode":0,"CommissionPercentProfit":0.0,"CommissionPercentSale":0.0,"Description":
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
not sure what ıs data but :) try this...

$(data).each(function()

>>>

$(JSON.stringify(data)).each(function()

or somehow try to use

JSON.parse(...)
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
or use

$.each(data, function(index){
  $('#idt > tbody:last-child').append("<tr><td>" + this.BinLocation + "</td><td>" + this.Description + "</td><td>" + this.Price + "</td></tr>");
});

Open in new window

Moti Mashiah.NET Developer

Author

Commented:
when I use manually data like u did with fiddle it works but when I do something like this. (like get it from the api)
function TestApi(){
              $.ajax({
                type: "GET",
                url: 'http://localhost:49175/api/items',
                dataType: "html",
                success: function (data) {
                    $(data).each(function() {
                      $('#idt > tbody:last-child').append("<tr><td>" + this.BinLocation + "</td><td>" + this.Description + "</td><td>" + this.Price + "</td></tr>");
                    });
                    }
                   });
                 }

Open in new window


it gives me syntax error.

I will try your last suggestion right now.
Thank you.
Sr. System Analyst
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
and my last 2 code should work...
Moti Mashiah.NET Developer

Author

Commented:
omg, thank you sooooooooo much.
this is it dataType json makes the different. LOL..

I did it soo many time and I don't know what happened to my mind this night.

Thank you again.
Moti Mashiah.NET Developer

Author

Commented:
The fundamental things to know :) return json when you get json, plus use your return data in your loop:) .

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.