-2

I have the following:

<script type="text/javascript" src="jquery.js"></script>

<script>
$.ajax({
    'async': true,
    'type': "get",
    'url': "service.php",
    'crossDomain': true,
    'dataType': 'json',
    'success': function (response) {

        if (response.result && response.result == "success") {
            if (response.data) {
                console.log("Found data: " + response.data);

            }
            else {
                console.log("Unable to find data");
            }
        }
        else {
            console.log("Unknown error:  " +
                (response.error ? response.error : ""));
        }
    },
    'error': function (response) {

        console.log("Error : " + JSON.stringify(response));
    }
});
</script>

Inside the service.php file is the the following:

<?php
$data = array("name" => "John Doe", "state" => "Somewhere","city" => 
"Someplace","zip" => "Somezip");
echo json_encode(array("result" => "success", "data" => $data));
?>

I need to change the code so instead of logging to the console it displays the data in the array in an HTML table. I am new to this and my coworkers and I have been challenged with attempting to figure this out for fun. We are all stuck as none of us use AJAX or JQUERY in our work. I have tried searching for an answer but I don't know enough about it to even know what to search for.

syee
  • 1
  • Check out this post for an approach that does this: https://stackoverflow.com/questions/8749236/create-table-with-jquery-append#answers. Put the for loop inside of your success callback. – Charlie Weems Feb 20 '18 at 23:18

2 Answers2

1

The two basic approaches are either for...in (shown) or jQuery's each().

var buffer = ['<table><thead><tr>'];
// draw the header
for(var name in response.data) buffer.push(`<th>${name}</th>`);
// draw the body
buffer.push("</tr></thead><tbody><tr>");
for(var name in response.data) buffer.push(`<td>${response.data[name]}</td>`);
buffer.push("</tr></tbody></table>");
// put it all together
var html = buffer.join('');
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
0

if (response.data) {
    var obj = response.data;
    var table = "<table><tr><th>Name</th><th>State</th><th>City</th><th>Zip</th></tr><tr><td>"+obj.name+"</td><td>"+obj.state+"</td><td>"+obj.city+"</td><td>"+obj.zip+"</tr></table>";
    $(".select-a-div-where-you-output-this").html(table);          
}
smacaz
  • 148
  • 8