Title: sforce.connection.query is not working for force.com sites
Tags: visualforce;soql;javascript;ajax-toolkit
Question: Iam trying to query records using AJAX Toolkit Javascript API through force.com sites.
But sforce.connection.query not working through sites. The same code working for internal users.
Please find the code snippet below:
function EditRecord(contid) {
alert('Contact I75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0'+contid);
sforce.connection.sessionId = "{!$Api.Session_ID}";
var result = sforce.connection.query("SELECT Id,FirstName,LastName,Email,Phone FROM Contact where Id='" + contid+ "'");
alert('result75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0'+result);
Can any one help me on how to access this without sessionId and force.com sites.


Here is another answer: This got pushed back up to the home page two years later but... yeah totally not happening. Think about the security implications. You'd have to have a session ID with API access for an unauthenticated guest user, and then anyone malicious would simply be able to type their own query into JavaScript console and search for whatever they want. Any objects they have write access to, they'd be able to just go nuts. If you had to make a certain object readable/writable to accomplish your use case, having a working unauthenticated API would be disastrous.
On the other hand Visualforce Remoting and Visualforce Remote Objects should work fine. But remember that anything you make available in JS can potentially be used maliciously by users so you need to ensure that the server side is not exposing anything that can be abused.

Here is another answer: I think you can't do in force.com sites. There is an idea for the same has been posted on community. You can up-vote it.
https://success.salesforce.com/ideaView?id=08730000000KMKsAAO
I don't know it this work or not. But you can give try to it.
Try using earlier version of ajax tool kit..i remember i too had some issue like same so i used "/soap/ajax/28.0/connection.js" to overcome the exception.

{'source': 'StackExchangeDataset', 'subset': 'salesforce.stackexchange.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:05/02/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<visualforce><soql><javascript><ajax-toolkit>', 'Title': 'sforce.connection.query is not working for force.com sites', 'ViewCount': 1252, 'id': 120119, 'user_AboutMe': '', 'user_AccountId': 3361026.0, 'user_DisplayName': 'Murali Mohan Mandadi', 'user_Reputation': 627.0, 'user_Views': 137.0, 'user_id': 3960.0}}