Sharepoint Multiple Item Creation Issue - javascript

I've been banging my head on this for a few days now, and seem to be no closer than before. Roughly it seems like the clientContext.executeQueryAsync is not working properly for creating multiple items in sharepoint. Here is the basic design. I created a web part in my share point site that connects to an html page. The page is on the home.aspx of the site, that has the following content added to it via a content page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" x-undefined="" />
<script type="text/javascript" src="/apps/dre/SiteAssets/Javascript/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/apps/dre/SiteAssets/Javascript/BatchControl.js"></script>
<script type="text/javascript" src="/apps/dre/SiteAssets/Javascript/jquery.SPServices-2014.01.min.js"></script>
<script type="text/javascript" src="/apps/dre/SiteAssets/Javascript/PageLoader.js"></script>
<script type="text/javascript" src="/apps/dre/SiteAssets/Javascript/BatchExecution.js"></script>
<script type="text/javascript">ExecuteOrDelayUntilScriptLoaded(function(){loadmasterpage();}, "sp.js")</script>
<title>Home Page</title>
</head>
<body>
<div id="batch" style="visibility:hidden">
<button id="batchcontrol" onclick="ExecuteBatchControl()">Create DRE Records</button>
</div>
</body>
</html>
So it's a very simple piece of HTML. The PageLoader library loads the button after SP.js is loaded.
function loadmasterpage()
{
$(document).ready(function() {
//alert("Here");
$('#batch').css('visibility','visible');
});
}
That's all the web content does in the Home.aspx page. It shows a simple HTML button. Now comes the baffling mystery. So if I click the button the BatchControl library executes the following code:
function ExecuteBatchControl()
{
createListItem();
}
function createListItem() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('Discrepancy Report');
for(x=0;x<4;x++){
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', "B2Batch");
oListItem.update();
clientContext.load(oListItem);
}
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}
function onQuerySucceeded() {
//alert('Item created: ' + oListItem.get_id());
alert('Success');
// $("input[Title='Caller ID']").val("");
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
It creates the records, but the onQuerySucceeded function never executes. If you remove the for...loop, it will execute, and it works fine. Why doesn't the batch coding work. It's almost like there is a stability issue with it, but I can't say. No one seems to know the answer here. Is it because I hooked up my html page to a web content web part? I am completely lost and baffled. PLEASE I NEED HELP!!!!!!

Related

Calling .jSignature() on div doesn't update the div

I got this code from the GitHub:
<script src="path/to/jSignature.min.js"></script>
<script>
$(document).ready(function() {
$("#signature").jSignature()
})
</script>
<div id="signature"></div>
But it doesn't pull anything up on the actual webpage. I would think there is more code required but I don't know where to start.
Here is a minimal working example
<!DOCTYPE html>
<html lang="en">
<head>
<lang>
<title>Minimal working jSignature Example</title>
<meta charset="UTF-8">
<!-- Files from the origin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://willowsystems.github.io/jSignature/js/libs/jSignature.min.js"></script>
<head>
<script>
$(document).ready(function() {
// Initialize jSignature
$("#signature").jSignature();
})
// ripped from the description at their the Github page
function getBase64Sig(){
// get the element where the signature have been put
var $sigdiv = $("#signature");
// get a base64 URL for a SVG picture
var data = $sigdiv.jSignature("getData", "svgbase64");
// build the image...
var i = new Image();
i.src = "data:" + data[0] + "," + data[1];
// and put it somewhere where the sun shines brightly upon it.
$(i).appendTo($("#output"));
}
</script>
<body>
Put your signature here:
<div id="signature"></div>
<button onclick="getBase64Sig()">Get Base64</button>
<div id="output"></div>
</body>
</html>
I hope you can go on from here.
It is really as simple as they describe it to be, only their description of the actual example is a bit lacking for beginners.

Simple youtube javascript api 3 request not works

i've tried to write a simple youtube request to search video with youtube javascript api v3.
This is the source code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
gapi.client.setApiKey('API_KEY');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q:'U2'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
When i load this page on google chrome (updated), nothing happens, the page remains blank.
I have request the API Key for browser apps (with referers) and copied in the method gapi.client.setApiKey.
Anyone can help me?
Thanks
Try this example here
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Search API Sample</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// How to search through a YouTube channel aka http://www.youtube.com/members
google.load('search', '1');
function OnLoad() {
// create a search control
var searchControl = new google.search.SearchControl();
// So the results are expanded by default
options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
// Create a video searcher and add it to the control
searchControl.addSearcher(new google.search.VideoSearch(), options);
// Draw the control onto the page
searchControl.draw(document.getElementById("content"));
// Search
searchControl.execute("U2");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="content">Loading...</div>
</body>
</html>
When you use <script src="https://apis.google.com/js/client.js?onload=onClientLoad" ..></script>
you have to upload the html file somewhere online or use XAMPP on your PC
To use html for searching YT videos, using Javascript on PC, as I know, we need to use other codings:
1- Use javascript code similar to this for API version 2.0. Except only the existence of API KEY v3.
2- Use the jQuery method "$.get(..)" for the purpose.
See:
http://play-videos.url.ph/v3/search-50-videos.html
For more details see (my post "JAVASCRIPT FOR SEARCHING VIDEOS"):
http://phanhung20.blogspot.com/2015_09_01_archive.html
var maxRes = 50;
function searchQ(){
query = document.getElementById('queryText').value;
email = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50'+
'&order=viewCount&q='+ query + '&key=****YOUR API3 KEY*****'+
'&callback=myPlan';
var oldsearchS = document.getElementById('searchS');
if(oldsearchS){
oldsearchS.parentNode.removeChild(oldsearchS);
}
var s = document.createElement('script');
s.setAttribute('src', email);
s.setAttribute('id','searchS');
s.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
}
function myPlan(response){
for (var i=0; i<maxRes;i++){
var videoID=response.items[i].id.videoId;
if(typeof videoID != 'undefined'){
var title=response.items[i].snippet.title;
var links = '<br><img src="http://img.youtube.com/vi/'+ videoID +
'/default.jpg" width="80" height="60">'+
'<br>'+(i+1)+ '. <a href="#" onclick="playVid(\''+ videoID +
'\');return false;">'+ title + '</a><br>';
document.getElementById('list1a').innerHTML += links ;
}
}
}
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<input type="text" value="abba" id="queryText" size="80">
<button type="button" onclick="searchQ()">Search 50 videos</button>
<br><br>
<div id='list1a' style="width:750px;height:300px;overflow:auto;
text-align:left;background-color:#eee;line-height:150%;padding:10px">
</div>
I used the original code that Tom posted, It gave me 403 access permission error. When I went back to my api console & checked my api access time, it was expired. So I recreated the access time for the api. It regenerated new time. And the code worked fine with results.
Simply i must make request from a web server.
Thanks all for your reply

Getting a checkbox to write a JavaScript cookie

I've got a page with a splash screen, where users select one of two languages in which the rest of the site will be displayed. Next to each language option is a "remember my choice", HTML form, checkbox. How can I have the selected checkbox write a cookie with the language preference, which would skip the splash screen on future visits?
May be you can use something like below, Note code not tested:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function setCookie(c_name,value,expiredays) {
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate)
}
function getCookie(c_name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1) {
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return null
}
onload=function(){
document.getElementById('linksNewWindow').checked = getCookie('linksNewWindow')==1? true : false;
}
function set_check(){
setCookie('linksNewWindow', document.getElementById('linksNewWindow').checked? 1 : 0, 100);
}
</script>
</head>
<body>
<div>Hi</div>
<input type="checkbox" id="linksNewWindow" onchange="set_check();">
</body>
</html>
This is a great reference for javascript cookies, http://www.quirksmode.org/js/cookies.html, I suggest doing this with PHP other than javascript simply because I the cookies and session functions are much more powerful with server-side scripting.
document.cookie
^ this is the js code that represents a pages cookies.

How to take this string from user at run time?

Look at the below code, this JavaScript is used to take a string (in a language other than English) and convert it into English.
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var content = document.getElementById('translation');
// Setting the text in the div.
content.innerHTML = '<div id="text">HELLO WORLD<\/div>
<div id="translation"/>';
// Grabbing the text to translate
var text = document.getElementById("text").innerHTML;
// Translate from Spanish to English, and have the callback of
// the request put the resulting translation in the
// "translation" div. Note: by putting in an empty string for
// the source language ('es') then the translation will
// auto-detect the source language.
google.language.translate(text, '', 'en', function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
google.setOnLoadCallback(initialize);
</script>
I want that the string "HELLO WORLD" must be entered by user at run time in a text field and then that string is passed to the div id text. So is this possible?
Hope you are referring to the document below:
http://code.google.com/apis/language/translate/v1/getting_started.html
Please refer to the section "Getting Started" where it says about "Signing up for an API key". This needs to be done before you could implement the code in your page.
Once done, make the modification to the script file which you include in the html page with your key.
Here, replace your key with "MY_KEY_STRING" in the bottom code and get started.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Language API Sample</title>
<script src="https://www.google.com/jsapi?key=MY_KEY_STRING"></script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
//Show the translate button
document.getElementById("translateButton").style.display = "";
}
google.setOnLoadCallback(initialize);
function translate() {
var text = document.getElementById("fromText").value;
google.language.translate(text, 'es', 'en', function(result) {
var translated = document.getElementById("toText");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
From:<input type="text" id="fromText"/>
To:<span id="toText"></span>
<input type="button" value="Translate" onclick="translate()" style="display: none;" id="translateButton">
</body>
</html>
HTML:
<form id="translate">
<textarea id="translate-me"></textarea>
<input type="submit" />
</form>
JavaScript:
var form = document.getElementById('translate')
var textarea = document.getElementById('translate-me')
form.onsubmit = function () {
google.language.translate(textarea.value, ...)
return false; // prevent default action (form submission)
}
Using jQuery or something similar would make this easier, of course.

Ajax not working

The code provided below doesn't show all the content of that page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript">
var rootdomain="http://"+window.location.hostname
alert(rootdomain);
function ajaxinclude(url) {
var url=rootdomain+url;
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.open('GET', url, false) //get page synchronously
page_request.send(null)
writecontent(page_request)
}
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 ||
page_request.status==200)
document.getElementById("write").innerHTML=page_request.responseText;
}
</script>
</head>
<body>
<div id="write">
</div>
<input type="button" value="Submit !" onclick="ajaxinclude('/songcake/index.php');"/>
</body>
</html>
Please Help
Thanks.
You need to add a closure that reacts upon the completion of the document loading process.
page_request.onreadystatechange = function() {
if(page_request.readystate == 4) {
// data handling here
}
}
As pointed out though, using jQuery will make things a lot easier.
Edit: To clarify, your AJAX call does check for the connection status (request.status), but not for the loading status (request.readystate). Your document probably did not load completely.
Here's a reference for the W3.org XMLHTTPRequest API: http://www.w3.org/TR/XMLHttpRequest/ .
Edit2: Btw, an <iframe> element would solve your problem with a lot less code.
Edit 3: Code
function ajaxinclude(url) {
//...
page_request.open('GET', url, false) //get page synchronously
//<> add onreadystatechange handler
page_request.onreadystatechange = function() {
if(page_request.readystate === 4) {
if(page_request.state === 200) {
//call function on success
writecontent(page_request.responseXML)
}
}
}
page_request.send(null)
}
Some additions:
if you put your ajax call into the <HEAD> you need to either create the dom elements you want to append data to as they are not available when the runtime runs through (which might lead to a dom error); or you need to add an on dom load event handler.
Synchronous calls are not properly implemented in some browsers and this might lead to errors too.
Why you should not use jQuery? You can do this simple as below..
$("#write").load("/songcake/index.php");
[EDITED]
Below you can see the completed code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript" src='scripts/jquery.js'></script>
</head>
<body>
<div id="write">
</div>
<input type="button" value="Submit !"
onclick="$('#write').load('/songcake/index.php');"/>
</body>
</html>
You can download jQuery from here : http://jquery.com/
The source for my answer you can find here : http://api.jquery.com/load/
try to use FireBug
FireBug show you state of your request.
If it 200 and you see that in reqest answer (in firebug) broken data then
you should check your index.php script

Categories

Resources