SOQL query in javascript

We can use SOQL in java-script on Visual Force pages or we can get it executed on click of a button or link present on detail page of a record. Below is the simple example of SOQL query in javascript on click of a button:
Javascript code:

{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
try{
var query = "SELECT Id,Name from Contact LIMIT 1";
var result = sforce.connection.query(query);
var arrayResult = result.getArray('records'); 
 
if(arrayResult.length == 0){
alert('There is no Contact');
}
else{
var contactName = arrayResult[0].Name;
alert(contactName);
}
}
catch(e){
alert('An error has occured');
}

Leave a Reply