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);
}
}