Getting a checkbox to write a JavaScript cookie - javascript

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.

Related

Sharepoint Multiple Item Creation Issue

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!!!!!!

Web-browser is not showing the output

I'm new to JavaScript and already encountered a problem. When I run the code and the browser pops up, it[browser] does not show anything. What I have is the testMethod.js file with one method:
function testMethod(num1, num2){
var value = num1 + num2;
return value;
}
and an HTML file from where I'm trying to run:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> My JavaScript</title>
<script language = "javascript" src = testMethod.js"></script>
</head>
<body>
<script language = "javascript" type = "text/javascript">
// var getValue = testMethod(2,3);
document.write("The result is " + testMethod(5,3));
</script>
<noscript>
<h3> This site requires JavaScript</h3>
</noscript>
</body>
</html>
The code is not implementing the result at all. It shows only a blank page browser.
It seems you have a quote missing in the html, it should say src="testMethod.js" where you are including the script in the first place.

JavaScript wouldn't display results of code

I tried creating a simple JavaScript file based on my adaption of source code from MDN.
My JavaScript code (loughshore_clubs.js) is as follows
<!--
var Club = “Ballinderry” ;
function ClubType(name){
if (name == “Ardboe”){
return name ;
} else{
return “I'm not from “+ name + “.”;
}
}
var clubs {myClub: ClubType(“Ardboe”), club2: ClubType(Club),
club3:
ClubType(“Moortown”)}
console.log(clubs.myClub); //Ardboe
console.log(clubs.club2); //Ballinderry
console.log(clubs.club3); //Moortown
/-->
And the HTML source (test.html) is
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8">
<title></title>
<meta name="generator" content="LibreOffice 4.2.4.2 (Linux)">
<meta name="created" content="20150514;0">
<meta name="changed" content="20150514;211357234273120">
<style type="text/css">
<!--
#page { margin: 2cm }
p { margin-bottom: 0.25cm; color: #000000; line-height:
120% }
a:link { so-language: en-US }
-->
</style>
</head>
<body>
<script src="scripts/loughshore_clubs.js" />
</body>
</html>
What's the matter? One thing I do realise is that I should avoid saving HTML files using LibreOffice and stick with Bluefish. (which I have on Mac o/s X Yosemite)
Remove the first and last lines of your script. HTML comment tags make no sense in a .js file.
Then replace each of your ” characters with a proper ".
You're also missing an = between clubs and { here: var clubs {myClub:...
After these changes you should have:
var Club = "Ballinderry";
function ClubType(name){
if (name == "Ardboe") {
return name;
} else {
return "I'm not from " + name + ".";
}
}
var clubs = {
myClub: ClubType("Ardboe"),
club2: ClubType(Club),
club3: ClubType("Moortown")
};
console.log(clubs.myClub); //Ardboe
console.log(clubs.club2); //Ballinderry
console.log(clubs.club3); //Moortown
This should work:
var Club = "Ballinderry" ;
function ClubType(name){
if (name == "Ardboe"){
return name ;
} else{
return "I\'m not from "+ name + ".";
}
}
var clubs = {
myClub: ClubType("Ardboe"),
club2: ClubType(Club),
club3: ClubType("Moortown")
};
console.log(clubs.myClub); //Ardboe
console.log(clubs.club2); //Ballinderry
console.log(clubs.club3); //Moortown
You're right, you should stop saving code with LibreOffice, because it changed all your " to “. I recommend using atom
And you didn't have an = when declaring the clubs variable.
Once again, get atom, and then download the linter package and use JShint. That should get you in the habit of writing nice code. I use it myself. Tweet to me if you need more help, I started out two months ago and I just completed the backend for my first Node.js app.
Edit: The other answer beat me to it, he should get the vote. :P

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