0

This question has been asked a couple of time here, but I haven't seen any of the responses work for me.

I have this piece of code built with cakePHP which successfully returns the data in JSON format, but I haven't been able to insert this JSON data into HTML div using Javascript.

$('.book-click').click(function (e) {
    e.preventDefault();
    var getHotel = $(this).attr('hotel-id');

    $.ajax({
        type: "POST",
        url: "<?php echo $this->Html->URL(array('action' => 'postBook')); ?>",
        data: {
            hotel: getHotel
        },
        cache: false,
        dataTye: "json",
        success: function (JSONObject) {
            var myData = "";
            for (var key in JSONObject) {
                if (JSONObject.hasOwnProperty(key)) {
                    myData += JSONObject[key];
                }
            }
            /*console.log(myData);*/
            alert(myData[key]["hotelname"]); //Giving undifined in alert

        }
    });
});

And this is the JSON data I get when I log the data on browser console:

[
    {
        "id": "11",
        "hotelname": "Sheraton hotel",
        "hoteladdress": "Abule Ikeja",
        "state": "Lagos State",
        "lga": "Ikeja",
        "hotelphone": "65645545454",
        "hotelwebsite": "",
        "adminphone": "6565656565",
        "adminemail": "[email protected]",
        "hotelemail": "",
        "facilities": ",,",
        "roomscategory": "Diplomatic",
        "standardrate": "150000",
        "leanrate": "",
        "aboutHotel": "",
        "requestStatus": "0",
        "createdOn": "1424360902",
        "updatedOn": "1424360902"
    }
]

How do I successfully, get this JSON data into HTML. Something like this:

$('#myDiv').html(myData[key]["hotelname"]);

I tried this, but it's just giving me Undefined.

Any help is appreciated.

3
  • 2
    Or $('#myDiv').html(JSONObject[0]["hotelname"]); without the loop - your loop creates a long string and not an object you can use to index your way into Commented Feb 24, 2015 at 10:24
  • @Rory@mplungjan With you guys approaches I still get "undefined". Commented Feb 24, 2015 at 10:35
  • so you are not sending application/json but some string that needs to be parsed first Commented Feb 24, 2015 at 12:57

2 Answers 2

4

Use $.each() to iterate:

success: function (JSONObject) {
    $.each(JSONObject, function(k,item){
       $('#myDiv').html(item.hotelname);
    });
}

var json = [
    {
        "id": "11",
        "hotelname": "Sheraton hotel",
        "hoteladdress": "Abule Ikeja",
        "state": "Lagos State",
        "lga": "Ikeja",
        "hotelphone": "65645545454",
        "hotelwebsite": "",
        "adminphone": "6565656565",
        "adminemail": "[email protected]",
        "hotelemail": "",
        "facilities": ",,",
        "roomscategory": "Diplomatic",
        "standardrate": "150000",
        "leanrate": "",
        "aboutHotel": "",
        "requestStatus": "0",
        "createdOn": "1424360902",
        "updatedOn": "1424360902"
    }
]

$.each(json, function(i, item){
    $('body').append(item.hotelname);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


As per your error, it seems that you either you don't have a valid json or that is a json string. So before loopin you have to parse it:

success: function (JSONObject) {
    var data = $.parseJSON(JSONObject); // parse it
    $.each(data, function(k,item){
       $('#myDiv').html(item.hotelname);
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

With approach, this is what I see in browser console: Uncaught TypeError: Cannot use 'in' operator to search for '394' in [{"id":"11","hotelname":"Sheraton hotel","hoteladdress":"Abule Ikeja","state":"Lagos State","lga":"Ikeja","hotelphone":"65645545454","hotelwebsite":"","adminphone":"6565656565","adminemail":"[email protected]","hotelemail":"","facilities":",,","roomscategory":"Diplomatic","standardrate":"150000","leanrate":"","aboutHotel":"","requestStatus":"0","createdOn":"1424360902","updatedOn":"1424360902"}]
@Michel See either your json is not json but string. so you need to parse it before using it. like jQuery.parseJSON(JSONObject)
Thanks a lot really appreciate. You save me time. I just needed to parse the JSON data. This is what I did: var data = $.parseJSON(JSONObject) Then used your approach with $.each() and it works fine. Thanks again
0
var myData = "";
for (var key in JSONObject) {
   if (JSONObject.hasOwnProperty(key)) {
       myData += JSONObject[key];
   }
}

myData here is simply just a string. Hence the call myData[key]["hotelname"] will return undefined, because you're trying to access something that does not exist.

Why not just use the result as-is from the Ajax call?

1 Comment

If I use the result as it is returned from ajax, that is whole JSON data. Meanwhile I need for example to get only the value "Sheraton Hotel" which belong to "hotelname".

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.