Reputation: 133
I am new to ajax and jquery, spend hours trying to figure it out just can't seem to find a solution online or anywhere else.
I am trying to figure out how I can (partially) group my result set to the desired output.
My json result set from ajax is:
{
"success":[
{
"id":8,
"subcategory":"SubCategory 1",
"subgroup":"Subgroup 1",
},
{
"id":9,
"subcategory":"SubCategory 1",
"subgroup":"Subgroup 2",
},
{
"id":10,
"subcategory":"SubCategory 2",
"subgroup":"Subgroup 3",
},
{
"id":11,
"subcategory":"SubCategory 2",
"subgroup":"Subgroup 4",
}
]
}
Trying to achieve this result:
<div class="profiles-wrapper">
<div class="profile-block-wrapper">
<div class="profile-block-title">SubCategory 1</div>
<div class="profile-subtags-wrapper">
<a href="" class="profile-tag">Subgroup 1</a>
<a href="" class="profile-tag">Subgroup 2</a>
</div>
</div>
<div class="profile-block-wrapper">
<div class="profile-block-title">SubCategory 2</div>
<div class="profile-subtags-wrapper">
<a href="" class="profile-tag">Subgroup 3</a>
<a href="" class="profile-tag">Subgroup 4</a>
</div>
</div>
</div>
The jquery/ajax part I have is. However I am a little bit lost as where to go from here.
$.ajax({
type:"POST",
url:"{{url('insert-ajax')}}",
data : form_data,
success: function(data) {
$.each(data.success, function(k, v) {
$("#inserted_data").append('<div class="profile-block-wrapper" >'+v.subcategory+'</div>');
});
}
});
Hope someone can help me out:)
Upvotes: 0
Views: 692
Reputation: 558
Assuming your ajax call is returning the expected result, you just need to add code for the actual grouping of the returned elements. In the code below the groupByCategory
function is used to create an associative array where the key is the subcategory, and the value contains the HTML for the links.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function loadData() {
data = {
"success": [{
"id": 8,
"subcategory": "SubCategory 1",
"subgroup": "Subgroup 1",
},
{
"id": 9,
"subcategory": "SubCategory 1",
"subgroup": "Subgroup 2",
},
{
"id": 10,
"subcategory": "SubCategory 2",
"subgroup": "Subgroup 3",
},
{
"id": 11,
"subcategory": "SubCategory 2",
"subgroup": "Subgroup 4",
}
]
};
var grouped = groupByCategory(data.success);
for (var k in grouped) {
$("#inserted_data").append('<div class="profile-block-wrapper" ><div class="profile-block-title">' + k + '</div><div class="profile-subtags-wrapper">' + grouped[k] + '</div></div>');
}
}
function groupByCategory(data) {
var groups = {};
$(data).each(function(k, v) {
if (!(v.subcategory in groups)) {
groups[v.subcategory] = "";
}
groups[v.subcategory] = groups[v.subcategory] + "<a href='' class='profile-tag'>" + v.subgroup + "</a>";
});
return groups;
}
$(document).ready(loadData);
</script>
<div id="inserted_data" class="profiles-wrapper">
</div>
</body>
</html>
Upvotes: 1