I’ve got a CFC performing a query via AJAX to get a list of image information/paths to display on my page. In my table I have a boolean column main to indicate if the image is the main image and thus displayed above all the other images.
Since I’m accessing the query results via AJAX, I need to create an array of the data before returning it to the page where my javascript function loops over the returned data and constructs the <img> tags.
How can I get either my CFC or my javascript loop to recognize the main boolean and move that image to first position for display on my page?
Here’s my CFC:
<cfquery name="project_images">
select path, title, alt, main from tbl_images where pid = #projects.pid#;
</cfquery>
<cfloop query="project_images">
<cfset imgStruct = structNew()>
<cfset imgStruct["path"] = path>
<cfset imgStruct["alt"] = alt>
<cfset imgStruct["title"] = title>
<cfset imgStruct["main"] = main>
<cfset ArrayAppend(imgArray, imgStruct)>
</cfloop>
<cfset local.response["images"] = #imgArray#>
<cfreturn local.response>
And my jQuery function:
$('.project_class').click(function(e){
e.preventDefault();
var theclass = $(this).attr('id');
var cat = 'planning';
$.getJSON("../cfc/projects.cfc?returnFormat=json&method=getProjects",
{"theclass":theclass, "cat":cat},
function(response){
$('#portfolio_item').html(response.html);
var imageData = response.images;
$.each(imageData, function(i, item) {
$('#portfolio_item').append('<img src="..' + item.path + '" />');
});
});
});
One option is sort the images within your SQL. Use a
CASEstatement to assign themainrecord a higher sort order than the others.Or you could check the
mainflag within the loop and usearrayPrependinstead ofarrayAppendwhen the flag is true.