0

I have a query Select name, age from users and I want it to return the content to jquery with a specific format:

var externalDataRetrievedFromServer = [
    { name: 'Bartek', age: 34 },
    { name: 'John', age: 27 },
    { name: 'Elizabeth', age: 30 },
];

On a php side so far I have:

$fetch = "SELECT name, age from users";
$result = $mysqli->query($fetch);
$data = array();    
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );

and on jquery site I have:

 $.ajax({
            url: './getJson.php', 
            type: "POST",
            data: {
                users: users
            },
            dataType:'text',
            success: function(ans)
            {

                alert(ans);

but it returns me data in a format:

[{"name":"Bartek","age":"34"},{"name":"John","age":"27"},{"name":"Elizabeth","age":"30"}]  

I need the specific format that I mentioned at the beginning of my post, because now my current logic (that I don't want to change) throws me an error: data.forEach is not a function in this line:

function buildTableBody(data, columns) {
        var body = [];

        body.push(columns);

        data.forEach(function(row) {
            var dataRow = [];

            columns.forEach(function(column) {
                dataRow.push(row[column].toString());
            })

            body.push(dataRow);
        });

        return body;
    }

where data is the data in a format that I have right now. So how can I change the format?


A little bit more details here:

I'm using buildTableBody() here:

function table(data, columns) {
            return {
                table: {
                    headerRows: 1,
                    body: buildTableBody(data, columns)
                }
            };
        }

However, when I changed the datatype from text to json, I'm getting the error:

Uncaught TypeError: Cannot read property 'toString' of undefined

from the method buildTableBody.

When I do alert(ans) now, I'm getting:

[object Object],[object Object],[object Object]

Do you have any clues how could I fix it?

---- another edit:

This is exactly what I want to achieve:

var externalDataRetrievedFromServer = [ { name: 'Bartek', age: 34 }, { name: 'John', age: 27 }, { name: 'Elizabeth', age: 30 }, ];

function buildTableBody(data, columns) { var body = [];

body.push(columns);

data.forEach(function(row) {
    var dataRow = [];

    columns.forEach(function(column) {
        dataRow.push(row[column].toString());
    })

    body.push(dataRow);
});

return body;

}

function table(data, columns) { return { table: { headerRows: 1, body: buildTableBody(data, columns) } }; }

var dd = { content: [ { text: 'Dynamic parts', style: 'header' }, table(externalDataRetrievedFromServer, ['name', 'age']) ] }

1
  • It's a quick hack but you could use str_replace on $data to swap the : and , around. Commented Oct 19, 2015 at 22:13

2 Answers 2

1

forEach for the rows, $.each for the columns.

DEMO HERE: http://jsfiddle.net/0cc3bgp2/

var x = '[{"name":"Bartek","age":"34"},{"name":"John","age":"27"},{"name":"Elizabeth","age":"30"}]';

var rows = $.parseJSON(x);

rows.forEach(function(row) {

    var dataRow = [];

    $.each(row, function(index, value) {
      dataRow.push(value);
    });

    //body.push(dataRow);
    console.log(dataRow);
});

// WILL LOG:
//
// ["Bartek", "34"]
// ["John", "27"]
// ["Elizabeth", "30"]
Sign up to request clarification or add additional context in comments.

1 Comment

@charlietfl OP said "because now my current logic (that I don't want to change) throws me an error: data.forEach is not a function in this line". I'm pointing out what can be parsed with forEach and what with $.each. Also, this is before OP's edit.
1

You are setting dataType:'text' so the response will be returned to success callback as a string.

Since there is no String.prototype.forEach() you get an error

Change to dataType:'json' and jQuery will parse the response to array internally.

It is not shown where you call buildTableBody() to be able to assist any further

4 Comments

Thanks for your quick response! Could you please check my updated question?
Still unknowns , where does columns come from? Not showing where the function table() is called
Sorry for not mentioning it before! I'm using an answer to this post github.com/bpampuch/pdfmake/issues/24 here, the code written bybpampuch - is that helpful for you in my case?
Have no interest in reading all that....questions should be self contained with all relevant code

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.