function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SS KarthickSS Karthick 

soql in javascript

Hi folks,
           Can anyone tell me how to execute Soql in java script(VisualforcePage) and gine me the some example



Thanks in advance
Karthick
Best Answer chosen by SS Karthick
jo devjo dev
Hi karthick,here i pasted sample code for your requirement.

visualforce page code:


<apex:page >
<script src="https://ap1.salesforce.com/soap/ajax/20.0/connection.js"></script>
<script>
function Queryvalue()
{

sforce.connection.sessionId = "{!$Api.Session_ID}";                      
var QryAccount="select Id,Name,Phone,Fax from Account";
var getrecord=sforce.connection.query(QryAccount);
var accountitem= new sforce.QueryResultIterator(getrecord);
var accarry = new Array();
    while (accountitem.hasNext())
    {
        var accnamearray = new Array();
        var record =accountitem.next();
        accnamearray[0]= record.Name;
        alert('Account Name'+accnamearray[0]);
    }
   
}
</script>
<apex:form >
<apex:commandButton value="Click me" onclick="Queryvalue();"/>
</apex:form>
</apex:page>


All Answers

logontokartiklogontokartik
Hi, You need to use AJAX toolkit to execute SOQL in javascript. Please see the link below, if you want to look at the examples, please go to Synchronous Examples section and you can see many there

http://www.salesforce.com/us/developer/docs/ajax/
jo devjo dev
Hi karthick,here i pasted sample code for your requirement.

visualforce page code:


<apex:page >
<script src="https://ap1.salesforce.com/soap/ajax/20.0/connection.js"></script>
<script>
function Queryvalue()
{

sforce.connection.sessionId = "{!$Api.Session_ID}";                      
var QryAccount="select Id,Name,Phone,Fax from Account";
var getrecord=sforce.connection.query(QryAccount);
var accountitem= new sforce.QueryResultIterator(getrecord);
var accarry = new Array();
    while (accountitem.hasNext())
    {
        var accnamearray = new Array();
        var record =accountitem.next();
        accnamearray[0]= record.Name;
        alert('Account Name'+accnamearray[0]);
    }
   
}
</script>
<apex:form >
<apex:commandButton value="Click me" onclick="Queryvalue();"/>
</apex:form>
</apex:page>


This was selected as the best answer
James LoghryJames Loghry
In addition to the Ajax toolkit, you could also write an Apex controller that performs the SOQL and returns the result.  Then you would invoke that Apex controller utilizing javascript and Remote Actions in Visualforce.  For examples of Remote Actions in use see the developer docs here: https://www.salesforce.com/us/developer/docs/pages/Content/pages_js_remoting.htm