0

ok so i have this function

success: function (data) {
    $('#chat').val(data);
    for (var i = 0, i < data.length, i++) {
        $.append("#ID: " + "#Mesaage");
    }
}

in which data is variable that holds a JSON array which is displayed like this:

{ID: Message}

How can I give it a format so it will simply print "ID: Message" without the curly brackets?

Scott
  • 1,863
  • 2
  • 24
  • 43
Ionut
  • 3
  • 4

4 Answers4

0

Data is a JSON element here, it acts like a normal object or class instance, you can access the value of ID by simply calling data.ID.

E.g.

$.append ("ID: " + data.ID);
Tom Doodler
  • 1,471
  • 2
  • 15
  • 41
0

Do you mean this (not sure what you mean by the curly brackets...)? Regardless, you need to amend the code for your loop first because you'll get a syntax error:

success: function (data) {

    // cache your DOM element
    $chat = $('#chat');

    for (var i = 0; i < data.length; i++) {
        $chat.append('ID: ' + data[i].Message);
    }
}
Andy
  • 61,948
  • 13
  • 68
  • 95
0

You can make use of Object.keys here:

success: function (data) {
    var key = Object.keys(data)
    $('#chat').val(key +":"+ data[key]);
},

A sample test is below:

var data = {"Id":"Message"};
var key = Object.keys(data);
$(document.body).append(key +":"+ data[key]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Jai
  • 74,255
  • 12
  • 74
  • 103
-1

$.append is invalid without a selector. You need to tell jQuery where you are placing the html

$(selector).append("#ID: " + "#Mesaage");

Also use proper for syntax with ; separators not ,

Also you can't do $('#chat').val(data) since data is an array

charlietfl
  • 170,828
  • 13
  • 121
  • 150