How could I return a list of records using only javascript, with no apex: elements.

My original approach was to use an apex:repeat like so:

   <apex:repeat value="{!attachments}" var="attach">               

In conjunction with a method in my controller.

But because the DOM of my page is created on the fly with jQuery, using apex elements won't really work.

Would anyone have any suggestions as to how I could return a list of records from one object with javascript and / or jQuery?

  • Do you know that inside of the repeat, you don't need to use <apex:elements>? You can bind the data directly however you want that.
    – dphil
    Apr 22, 2014 at 14:24
  • Oh I know, but that repeat would have to be added dynamically with jQuery, which wouldnt really work I'm afraid.
    – Daft
    Apr 22, 2014 at 14:26
  • 1
    Alright, just making sure. I know a year or two back, I had some jQuery dynamically building styling and doing some other fun stuff paired with an <apex:repeat>. Looks like the other guy has it handled below though.
    – dphil
    Apr 22, 2014 at 14:29

2 Answers 2


The easiest way I've found is to make use of the AJAX Toolkit and the sforce.connection.query method (remember to change the actual query to what you're after).

<script type="text/javascript">
    var __sfdcSessionId = '{!GETSESSIONID()}';

<script src="../../soap/ajax/30.0/connection.js" type="text/javascript"></script>

<script type="text/javascript">
    function doQuery
            "Select Id, Name, Industry From Account order by Industry",
                onSuccess: onSuccess,
                onFailure: onFailure,
                source: { //state that you need when the callback is called }

    function onSuccess(result, source) 
        var records = result.getArray("records");

        for (var i = 0; i < records.length; i++) 
            var record = records[i];
            log(record.Name + " -- " + record.Id);

    function onFailure(error, source) 
        // Handle failure

This is a cut down version of the sample here.

  • Works perfectly! Good lad Alex!
    – Daft
    Apr 22, 2014 at 14:53

Another recommended route is to use Javascript Remoting for Visualforce. One of the advantages of JS remoting over the AJAX Toolkit is the ability to setup and control your logic of what is returned in apex. Here is a stubbed out example:

function getAttachments() {

        function(result, event){
            if (event.status) {
                //success, do what you need to do with jQuery
            } else {
                //handle errors
        {escape: true}

You would also need a corresponding controller and @RemoteAction method

global static List<Attachment> findAttachments() { ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.