tonoslfx
tonoslfx

Reputation: 3442

jquery convert array to string html

as the title stated. how do i do that? i read in some forum to use stringify? and how do i use it?

PHP:

$notes = $db->query("SELECT * FROM notes WHERE id_user = '$id_user'");
$output = array();
while($note = $notes->fetch_assoc()) {
  $noting = '<span class="block_note">'.$note['note'].'</span>';
  array_push($output, $noting);
}
$data['ok'] = true;
$data['message'] = $output;
echo json_encode($data);

jQuery:

$.get("include/get_details.php?id_user=1",function(data){
  if (data.ok){
     $.each(data, function(key,id){
        $("#notes").append(data.message);
     })

  }
}, "json");

Output:

{
"ok":true,
"message":[
  "<span class=\"block_note\">note1<\/span>",
  "<span class=\"block_note\">note2<\/span>",
  "<span class=\"block_note\">note3<\/span>"
]
}

Upvotes: 0

Views: 3120

Answers (5)

Salman Arshad
Salman Arshad

Reputation: 272026

data.message is a JavaScript Array, so you can just use the Array.join method:

...
if (data.ok){
    $("#notes").append(data.message.join(""));
}
...

The Array object also provides various iteration methonds which you should find useful.

PS: you can also write your PHP code like this:

$data = array();
$data['message'] = array();
while($note = $notes->fetch_assoc()) {
    $data['message'][] = '<span class="block_note">' . $note['note'] . '</span>';
}
$data['ok'] = true;

Upvotes: 1

Ryan
Ryan

Reputation: 3815

$.get("include/get_details.php?id_user=1",function(data){
  if (data.ok){
     $.each(data.message, function(key,id){
     $("#notes").append(id);
    });
  }
}, "json");

Check out the fiddle here http://jsfiddle.net/ryan_s/58cLY/

Upvotes: 1

rmorero
rmorero

Reputation: 596

I believe the easiest way to do this would be to use the jQuery .toArray() function, and then javascript join().

Like this:

var myArray = $(".block_note").toArray();
myArray.join("");

Upvotes: 1

Riz
Riz

Reputation: 10236

array.join(separator)

In you case:

message = data.message;
html = message.join('');

Upvotes: 1

spicavigo
spicavigo

Reputation: 4224

$.get("include/get_details.php?id_user=1",function(data){
  if (data.ok){
     $.each(data.message, function(key,value){
        $("#notes").append(value);
     })

  }
}, "json");

Upvotes: 2

Related Questions