The List Schema for Survey List is quite different from the Custom Lists.
Every Question is added as the List column(Field) and
Every Response to questions is added as List Item.
To retrieve the Survey question and and To submit the response to List via Client Object Model,
do the following.
1)Load the reference of sp.js and Load the address of function to be called as below
SP.SOD.executeOrDelayUntilScriptLoaded(DisplaySurveyQ,'SP.js');
2)Define the function.
var surveyItems = null;
var surveyFields=null;
var surveyList = null;
var oneField = null;
function DisplaySurveyQ()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
// of your desired target list:
surveyList = web.get_lists().getByTitle('surveylistName');
//alert(surveyList);
var caml = new SP.CamlQuery();
surveyItems = surveyList.getItems(caml);
surveyFields=surveyList.get_fields();
oneField = surveyFields.getByInternalNameOrTitle("Title");
//alert(surveyFields);
//alert(surveyItems);
//listOperations
context.load(oneField);
context.load(surveyList);
context.load(this.surveyItems);
context.load(this.surveyFields);
context.load(list);
alert(list);
3) Create callback handlers in this function
var success = Function.createDelegate(this, this.onSuccess);
var failure = Function.createDelegate(this, this.onFailure);
4)Execute an async query in this function
context.executeQueryAsync(success,failure);
}
5)Define Function On success full operation.
// Async query succeeded.
function onSuccess(sender, args) {
// for example iterate through list items or fields and assign the value to html controls like div, uls etc
var listEnumerator = surveyItems.getEnumerator();
var listFieldEnumerator = surveyFields.getEnumerator();
var Fields=surveyList.get_fields();
var Questions=new Array();
var qCount=0;
//iterate though all of the Questions and get the recently added question from Survey
var Count=0;
while (listFieldEnumerator .moveNext()) {
var currentField=listFieldEnumerator.get_current();
//alert(currentField.get_fieldTypeKind());
if(currentField.get_fieldTypeKind()==SP.FieldType.choice)
{
//alert(currentField.get_title());
Questions[qCount]=currentField;
}
Count= Count+ 1;
}
var currentField=Questions[qCount];
var FieldsChoices=currentField.get_choices() ;
// save the current questions internal name in hidden field , which will be helpful while submitting the response.
input type='hidden' name='CurrentQuestion' id='CurrentQuestion' value='"+currentField.get_internalName()
var divSurvey='generateRequiredHtml'
document.getElementById('generateRequiredHtmlandAssignThisIDmustPresent').innerHTML =divSurvey ;
}
6)Pass on the exception to UI by defining the failure function
// Async query failed.
function onFailure(sender, args)
{
alert(args.get_message());
}
7)To Submit Response to Survey List
function SubmitVote()
{
//Get the Group of radio Buttons for vote options and get the selected value
//alert($("input[name='grpRadio']:checked").val());
if (undefined === $("input[name='grpRadio']:checked").val())
{
// do something
alert('Please select any response');
return;
}
// Get the current context
var context = new SP.ClientContext.get_current();
// Get the current site (SPWeb)
var web = context.get_web();
// Get the survey list
var list = web.get_lists().getByTitle('surveyListname');
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreateInfo);
var response=document.getElementById('SelectedRadio').value;(response stored in hidden field)
var questionId=document.getElementById('CurrentQuestion').value (question's internal name stored in hidden field)
/* Set fields in the item.
In managed code, this would be listItem[fieldname] = value.
In Javascript, call listItem.set_item(fieldName,value).
*/
listItem.set_item(questionId, response);
listItem.update();
// Create callback handlers
var success = Function.createDelegate(this, this.onSuccessVote);
var failure = Function.createDelegate(this, this.onFailureVote);
// Execute an async query
context.executeQueryAsync(success,failure);
}
// Async query succeeded.
function onSuccessVote(sender, args) {
alert('Thanks for responding Survey');
// Refresh the page.
// SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
// Async query failed.
function onFailureVote(sender, args) {
alert(args.get_message());
}
8)Add the above code lines in txt file as follows
///less than sign![CDATA[ -- above code lines here--
]]grater than sign script ends
//static html here inside div div to assign generated html)
9)To debug above code place debugger; after any code line,which helps you to debug client object code with Visual Studio debugger.
10)Save this file as .txt file and upload to library and refer this link in content editor webpart
This post is for good maintainability of code on Sharepoint site itself . That's gr8.. . :)
Download Source Code
Every Question is added as the List column(Field) and
Every Response to questions is added as List Item.
To retrieve the Survey question and and To submit the response to List via Client Object Model,
do the following.
1)Load the reference of sp.js and Load the address of function to be called as below
SP.SOD.executeOrDelayUntilScriptLoaded(DisplaySurveyQ,'SP.js');
2)Define the function.
var surveyItems = null;
var surveyFields=null;
var surveyList = null;
var oneField = null;
function DisplaySurveyQ()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
// of your desired target list:
surveyList = web.get_lists().getByTitle('surveylistName');
//alert(surveyList);
var caml = new SP.CamlQuery();
surveyItems = surveyList.getItems(caml);
surveyFields=surveyList.get_fields();
oneField = surveyFields.getByInternalNameOrTitle("Title");
//alert(surveyFields);
//alert(surveyItems);
//listOperations
context.load(oneField);
context.load(surveyList);
context.load(this.surveyItems);
context.load(this.surveyFields);
context.load(list);
alert(list);
3) Create callback handlers in this function
var success = Function.createDelegate(this, this.onSuccess);
var failure = Function.createDelegate(this, this.onFailure);
4)Execute an async query in this function
context.executeQueryAsync(success,failure);
}
5)Define Function On success full operation.
// Async query succeeded.
function onSuccess(sender, args) {
// for example iterate through list items or fields and assign the value to html controls like div, uls etc
var listEnumerator = surveyItems.getEnumerator();
var listFieldEnumerator = surveyFields.getEnumerator();
var Fields=surveyList.get_fields();
var Questions=new Array();
var qCount=0;
//iterate though all of the Questions and get the recently added question from Survey
var Count=0;
while (listFieldEnumerator .moveNext()) {
var currentField=listFieldEnumerator.get_current();
//alert(currentField.get_fieldTypeKind());
if(currentField.get_fieldTypeKind()==SP.FieldType.choice)
{
//alert(currentField.get_title());
Questions[qCount]=currentField;
}
Count= Count+ 1;
}
var currentField=Questions[qCount];
var FieldsChoices=currentField.get_choices() ;
// save the current questions internal name in hidden field , which will be helpful while submitting the response.
input type='hidden' name='CurrentQuestion' id='CurrentQuestion' value='"+currentField.get_internalName()
var divSurvey='generateRequiredHtml'
document.getElementById('generateRequiredHtmlandAssignThisIDmustPresent').innerHTML =divSurvey ;
}
6)Pass on the exception to UI by defining the failure function
// Async query failed.
function onFailure(sender, args)
{
alert(args.get_message());
}
7)To Submit Response to Survey List
function SubmitVote()
{
//Get the Group of radio Buttons for vote options and get the selected value
//alert($("input[name='grpRadio']:checked").val());
if (undefined === $("input[name='grpRadio']:checked").val())
{
// do something
alert('Please select any response');
return;
}
// Get the current context
var context = new SP.ClientContext.get_current();
// Get the current site (SPWeb)
var web = context.get_web();
// Get the survey list
var list = web.get_lists().getByTitle('surveyListname');
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreateInfo);
var response=document.getElementById('SelectedRadio').value;(response stored in hidden field)
var questionId=document.getElementById('CurrentQuestion').value (question's internal name stored in hidden field)
/* Set fields in the item.
In managed code, this would be listItem[fieldname] = value.
In Javascript, call listItem.set_item(fieldName,value).
*/
listItem.set_item(questionId, response);
listItem.update();
// Create callback handlers
var success = Function.createDelegate(this, this.onSuccessVote);
var failure = Function.createDelegate(this, this.onFailureVote);
// Execute an async query
context.executeQueryAsync(success,failure);
}
// Async query succeeded.
function onSuccessVote(sender, args) {
alert('Thanks for responding Survey');
// Refresh the page.
// SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
// Async query failed.
function onFailureVote(sender, args) {
alert(args.get_message());
}
8)Add the above code lines in txt file as follows
///less than sign![CDATA[ -- above code lines here--
]]grater than sign script ends
//static html here inside div div to assign generated html)
9)To debug above code place debugger; after any code line,which helps you to debug client object code with Visual Studio debugger.
10)Save this file as .txt file and upload to library and refer this link in content editor webpart
This post is for good maintainability of code on Sharepoint site itself . That's gr8.. . :)
Download Source Code
12 comments:
hello swati thanks for posting this nice article .can you tell me how we can show list data on a page as we dont have gridview or list view like server side controls.
Hi Promod,
You can directly customize listview webwart instead of gridview.
Or use managed client object model
http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/fetching-lists-from-sharepoint-2010-site-using-client-object-model/
Thanks a lot Swati for your suggestion.
But the problem is that i dont have to access to visual studio so i can not use managed client object model as well as list view control.
i have to do all the things only content editor webpart and through javascript client object model.
also i want to know how to join two list using javascript client object model and upload file to list through same approach.
waiting for your responce.
please help.
instead of sticking to client object model.you can follow the OOB approaches
1)In SPD , you can create Dataview webpart and customize it
http://swatipoint.blogspot.in/2013/03/how-to-deploy-custom-list-forms-with.html
2) For joining multiple list , Use content by query WP
(also check few limitations)
http://www.n8d.at/blog/limitation-of-content-query-web-part-cqwp/
for aggregation
http://msdn.microsoft.com/en-us/library/ff649417.aspx
Thanks Swati for your valuable suggestion.
but the problem is that i dont have to access right of visual studio and sharepoint designer caml query builder tool as well as central admin access right . i have to provide solution only and only using content editor webpart through javascript client object model that is why i m asking for that approach
please help.
If you download the code attached in this post and check the source code.
You will find that ,html is constructed dynamically (iterating through resultset) .this can help you.
Hello swati ,
I have a requirement to send an email with attachment using ECMA
script .
Please help how can i achieve this functionality
Hi Swati ,
I want to retrive all versions data from sharepoint list using ECMA
please help me how can achive this .
any help will be appriciaated.
it is very urgent
Hi Swati,
I am doing the almost the same thing but it is showing me "Specified Argument was out of range of valid values Parameter name: value".
I am looping through the stored internalNames of the questions and getting their responses.
if its is possible than help.
i have one survey list and i want to lode qus according to there roll e.g. if there is 10 qus i want to lode only 5 qus.
Hi Swati,
I have stucked when i want to create a new question using ecma.
Have you any iputs on that .
Thanks in Advace.
Regards,
Akshay
Post a Comment