3

I would like to fill an HTML table with a JavaScript array. But, it doesn't work and I don't know why, my "innerHTML" is not interpreted.

My variable contains the good value, but when I do this :

document.getElementById("title").innerHTML = title;

It doesn't work.

This is my code:

var title = "";
var link = "";
var date = "";
var image = "";

function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "my_url");
xhr.onload = function () {
    if (xhr.responseText == 0) {
        alert("Vous n'avez poster aucun post");

    } else {
        var posts_array = JSON.parse(xhr.responseText);

        for (var i = 0; i < posts_array.length; i++)
        {
            title = posts_array[i][0];
            link = posts_array[i][1];
            date = posts_array[i][2];
            image = posts_array[i][3];

        }
    document.getElementById("title").innerHTML = title;
    }
}
xhr.send();
}

This is my HTML :

<table id="posts">
                <tr>
                    <th id="test">Titre</th>
                    <th>Lien</th>
                    <th>Date</th>
                    <th>Image</th>
                </tr>
                <tr>
                    <td id="title"></td>
                    <td id="link"></td>
                    <td id="date"></td>
                    <td id="image"></td>
                </tr>
            </table>
3
  • Can you supply your HTML? Commented Jul 15, 2016 at 9:52
  • 2
    have you checked that xhr.responseText definitely contains data? Also, you are aware that on each loop through posts_array you are overwriting the title variable with the latest value from the loop? Did you mean to concatenate them? Commented Jul 15, 2016 at 9:54
  • first alert the title in the loop, to check, Commented Jul 15, 2016 at 9:57

3 Answers 3

4

You're assigning the value of title inside your loop and then setting the innerHTML of an individual cell to title. Assuming your responseText is formatted correctly, the posts table will only ever contain the last element in your array. It seems like you need to create a new table row for each item in posts_array and add it to the posts table to get your intended result.

e.g.

var t = "";
for (var i = 0; i < posts_array.length; i++){
      var tr = "<tr>";
      tr += "<td>"+posts_array[i][0]+"</td>";
      tr += "<td>"+posts_array[i][1]+"</td>";
      tr += "<td>"+posts_array[i][2]+"</td>";
      tr += "<td>"+posts_array[i][3]+"</td>";
      tr += "</tr>";
      t += tr;
}
document.getElementById("posts").innerHTML += t;
Sign up to request clarification or add additional context in comments.

Comments

2

You have 3 errors in your code.

  1. You overriding title, link, date and image on each iteration.
  2. You setting only title, I think you want to set all data.
  3. (Posible error) You setting only 1 post into table, probably you want to see them all.

Easiest (and most common) way to create table from array is build HTML string (with table markup), and append it to table. Unfortunately IE do not support appending html into table, to solve this you may use jquery (it will create Elements from html and append them).

Example:

var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
    //create html table row
    table_html += '<tr>';
    for( var j = 0; j < columns.length; j++ ){
        //create html table cell, add class to cells to identify columns          
        table_html += '<td class="' +columns[j]+ '" >' + posts_array[i][j] + '</td>'
    }
    table_html += '</tr>'
}
$( "#posts" ).append(  table_html );

Another way is to use table dom api, this will not require jQuery:

var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table = document.getElementById('posts');

for (var i = 0; i < posts_array.length; i++)
{
    var row = table.insertRow( -1 ); // -1 is insert as last
    for( var j = 0; j < columns.length; j++ ){
        var cell = row.insertCell( - 1 ); // -1 is insert as last
        cell.className = columns[j]; //
        cell.innerHTML = posts_array[i][j]
    }
}

1 Comment

The 2nd one very helpful , thank you
0

It doesn't work for me.

I want to display wordpress posts into an HTML table.

My JS :

function get_posts() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "myUrl");
    xhr.onload = function () {
        if (xhr.responseText == 0) {
            alert("Vous n'avez poster aucun post");

        } else {
            var posts_array = JSON.parse(xhr.responseText);
            var columns = ['title', 'link', 'date', 'image']
            var table_html = '';
            for (var i = 0; i < posts_array.length; i++)
            {
                //create html table row
                table_html += '<tr>';
                for (var j = 0; j < columns.length; j++) {
                    //create html table cell, add class to cells to identify columns          
                    table_html += '<td class="' + columns[j] + '" >' + posts_array[i][j] + '</td>'
                }
                table_html += '</tr>'
            }
        }
        $("#posts").append(table_html);
    }
    xhr.send();
}

My HTML :

<table id="posts">
                    <tr>
                        <th id="test">Titre</th>
                        <th>Lien</th>
                        <th>Date</th>
                        <th>Image</th>
                    </tr>
                </table>

My Web service (i'm using wordpress) :

global $current_user;
if(is_user_logged_in){
$current_user = wp_get_current_user();
}

$array = array();
$posts_array = array('author' => $current_user->ID, "post_type" => "alertes", "orderby" => "date", "order" => "DESC", "post_status" => "publish", "posts_per_page" => "10");

$posts = new WP_Query($posts_array);

if($posts->have_posts()){
    while($posts->have_posts()){
        $posts->the_post();

        $post_array = array(get_the_title(), get_the_permalink(), get_the_date(), wp_get_attachment_url(get_post_thumbnail_id()));
        array_push($array, $post_array);

    }
        echo json_encode($array);

}

else {
    echo '0';
}

Comments

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.