2

I'm calling Web Service API with php and response is in JSON which is formatted like this:

"hits": {
"found": 23,
"start": 0,
"hit": [
  {
    "id": "data_upload_20150608_97",
    "fields": {
      "district": "City name",
      "street": "Street name",
      "building_name": "Blue tower",
      "description": "Some description text.",
      "latlon": "0.0,0.0",
      "website": "http:\/\/www.example.com/id"
    }
}

Response is then retrieved with $.getJSON as following:

$("#myForm").submit(function(event) {
        event.preventDefault();
        var search_term = $("#search_txt").val()
        if(search_term.length > 0) {
            $.getJSON("assets/php/search.php?query="+search_term, function(result) {
                process_result(result);
            });
        }
    });

What I'm trying to achieve is to separate fields from JSON in the HTML structure something like:

<div id="result">
<div class="row">
    <div class="large-6">
        <h2>City name</h2>
        <div>District: City name</div>
        <div>Street: Street name</div>
        <div>Building name: Blue tower</div>
    </div>
    <div class="large-3">
        <div>Lat Lon: 0.0,0.0</div>
        <div>Description: Some description text.</div>
        <a href="http://www.example.com/id">Link</a>
    </div>
</div>

I've made a function to process results and display it, but not getting far using $.each and .append. I'm not a JS person but here is function, which looks quite messy, even for me:

function process_result(response_string) {
        $.each(response_string, function(index, hit) {
            $("#result").append(
                $( '<div />', { 'class': 'row' } ).append(
                    $( '<div />', { 'class': 'large-6' } ).append(
                        $.each(hit, function(key, value) {
                            if(key == "District") {
                                $("#result").append("<h2>"+value+"</h2>");
                            }
                            if(key == "URL") {
                                $("#result").append("<a href="+value+">Link</a>");
                            }
                            else {
                                $("#result").append("<div>"+key+": "+value+"</div>");
                            }
                        })
                    )
                )
            )
        })
    }

This is not giving me desired result ie. row element is printed on the bottom. I might be way off here, and not sure is using $.each here is best way to go but I'm out of clue right now. If anyone have a better way to approach this, would love to hear.

Also, my first question on SO!

EDIT:

I had to get away from processing JSON in PHP and only pass raw JSON to JS and then use following to get the DOM structure as needed:

function process_result(response_string) {
    var obj = JSON.parse(JSON.stringify(response_string));
    //console.log(obj.hits.hit);
    $("#result").empty();
    for(var i in obj.hits.hit){
        var item = obj.hits.hit[i]['fields'];
        var html = '';
        html += '<div class="row"><div class="large-6 columns small-12">';
        html += '<h2>'+item['district']+'</h2>';
        html += '<div>District: '+item['district']+'</div>';
        html += '<div>Street: '+item['street']+'</div>';
        html += '<div>Building: '+item['building_name']+'</div>';
        html += '</div>';
        html += '<div class="large-6 columns">';
        html += '<div>Lat Lon: '+item['latlon']+'</div>';
        html += '<div>Description: '+item['description']+'</div>';
        html += '<a href="'+item['website']+'">Link</a>';
        html += '</div>';
        $('#result').append(html);
      }
    }
perke
  • 50
  • 7

2 Answers2

2

One way to do it: https://jsfiddle.net/Lzbt5tr1/1/

var result = '{"hits": {"found": 23,"start": 0,"hit": [{"id": "data_upload_20150608_97","fields": {"district": "City name","street": "Street name","building_name": "Blue tower","description": "Some description text.","latlon": "0.0,0.0","website": "http:\/\/www.example.com/id"}}]}}';

var obj = JSON.parse(result);
console.log(obj.hits.hit);
for(var i in obj.hits.hit){
    var item = obj.hits.hit[i]['fields'];
    var html = '';
    html += '<div class="row"><div class="large-6">';
    html += '<h2>'+item['district']+'</h2>';
    html += '<div>District: '+item['district']+'</div>';
    html += '<div>Street: '+item['street']+'</div>';
    html += '<div>Building: '+item['building_name']+'</div>';
    html += '</div>';
    html += '<div class="large-3">';
    html += '<div>Lat Lon: '+item['latlon']+'</div>';
    html += '<div>Description: '+item['description']+'</div>';
    html += '<a href="'+item['website']+'">Link</a>';
    html += '</div>';
    $('#result').append(html);
}
Leeish
  • 5,203
  • 2
  • 17
  • 45
  • I can clean up the key/vals if you want, but you've sort of already got that part down. I personally prefer to write out the HTML when doing this in JS. It's more verbose, but in the end to me easier to read. – Leeish Jun 18 '15 at 22:31
  • I'm getting `SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data var obj = JSON.parse(result);` but I might done something wrong... How would I use this with $.getJSON in the above code? – perke Jun 19 '15 at 07:35
  • Edited question to reflect on changes I did, thanks for heads up @Leeish – perke Jun 19 '15 at 13:20
  • I just threw your JSON string in there. I think I had to wrap it in `{}`. But once it's an object in the form your described this should work. – Leeish Jun 19 '15 at 14:04
1

Have you ever considered using JS template engines? If not, it is worthwhile to take a look at this (this may save you some time).

Check out this posting please.

Community
  • 1
  • 1
Alp
  • 3,027
  • 1
  • 13
  • 28