Retrieving cookie on subdomain that was created on main domain - javascript

I have been researching not only this site, but also around the web and cannot find the solution. I have full access to both domains.
The code in my main domain (test.com.es) is:
<script type="text/javascript">
jQuery(document).ready(function($){
$('.quote_button').click(function(e) {
//create product number cookie
var itemname = $('.colors_productname span').html();
document.cookie= 'product_id=' + itemname + '; path=/';
(I have entered the following after path=/';domain = "test.com.es";) - This is still not working.
`e.preventDefault();
document.location.href='http://contact.test.com';
});
});
</script> `
In my subdomain I have the code:
Product SKU* <input class="right" id="skew" size="30" name="skew" value="" type="text"/><br/>
<script type="text/javascript">
$(document).ready(function() {
function getCookie()
{
var name = 'product_id=';
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0)
{
var productname = c.substring(name.length,c.length);
return productname;
}
}
}
var product = getCookie();
$('#skew').val(product);
});
</script>
Can someone please assist in why this is not pulling through?
Thanks
DB

Related

JavaScript is throwing HTML errors

I'm new to JavaScript and am trying to work through some errors. I've researched sites and made a few changes but still having trouble. Any assistance is appreciated.
The goal is to take selected items on a SharePoint list and click a button that will open an email with list data.
The errors are below:
SCRIPT1002: SCRIPT1002:
HTML1423: Malformed start tag. Attributes should be separated by whitespace.
HTML1409: Invalid attribute name character. Attribute names should not contain ("),('),(<), or (=).
HTML1422: Malformed start tag. A self closing slash should be followed by a U+003E GREATER-THAN SIGN (>).
HTML1423: Malformed start tag. Attributes should be separated by whitespace. Email.aspx (807,105)
HTML1409: Invalid attribute name character. Attribute names should not contain ("),('),(<), or (=).
Here's the latest code...
<script type="text/javascript"> </script>
<script src=".../jquery-1.12.4.js"</script>
<script src=".../jquery.min"</script>
<script src=".../sprestlib.bundle.js"</script>
<script src=".../vue.min.js"</script>
<script src=".../jquery-3.5.1.js"</script>
function clickMethod() {
var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
sprLib.list('DRLs').items({
listCols: {
iD: {dataName:'ID'},
drlId: {dataName:'Title'},
artifactIdCopy: {dataName:'ArtifactID'},
assessmentId: {dataName:'AssessmentIDCopy'},
dueDate: {dataName:'TaskDueDate'},
AOREmails: {dataName:'AOREmails'},
startDate: {dataName:'Assessment_x0020_ID_x0020_LU_x00'},
teamMemberEmails: {dataName:'TeamMemberEmails'},
artifactLink: {dataName: 'Artifact_x0020_Link'},
drlItemLink: {dataFunc:function(objItem){return 'View DRL'}}
},
queryOrderby: 'Title';
})
.then(findSelectedItems(arrData, items);
.catch(function(errMsg){console.error(errMsg) });
}
function findSelectedItems(spData, selectedItems){
var emailBody = '';
for(var i = 0; i < selectedItems.length; i++){
var itemID = selectedItems[i].id;
for(var j = 0; j < spData.length; j++){
if (spData[i].iD == itemID){
emailBody += "Title: " + spData[i].drlId + "\r\n";
}
}
}
sendMail(emailBody);
}
function sendMail(bodyString) {
var message = encodeURIComponent(bodyString);
//var yourMessage = document.getElementById('AORNames');
var subject = document.getElementById('DRLID').value;
var emails = document.getElementById('AOREMails').value;
var mail = "mailto:" + emails + "?subject=" + subject + "&body=" + message;
window.location.href = mail;
}
</script>
<button #click="clickMethod()">Send Email</button>
I recommend splitting out the javascript into separate files. Then you'd just need to do <script src='/my-new-file.js'></script> in the html file instead of mixing and trying to match like what's happening at the moment.
Alternatively if you want to keep it like you have it now, on the first line, removing the closing script tag and move all of the other script tags outside. Like this:
<body><button #click="clickMethod()">Send Email</button>
<script src=".../jquery-1.12.4.js"</script>
<script src=".../jquery.min"</script>
<script src=".../sprestlib.bundle.js"</script>
<script src=".../vue.min.js"</script>
<script src=".../jquery-3.5.1.js"</script>
<script type="text/javascript">
function clickMethod() {
var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
sprLib.list('DRLs').items({
listCols: {
iD: {dataName:'ID'},
drlId: {dataName:'Title'},
artifactIdCopy: {dataName:'ArtifactID'},
assessmentId: {dataName:'AssessmentIDCopy'},
dueDate: {dataName:'TaskDueDate'},
AOREmails: {dataName:'AOREmails'},
startDate: {dataName:'Assessment_x0020_ID_x0020_LU_x00'},
teamMemberEmails: {dataName:'TeamMemberEmails'},
artifactLink: {dataName: 'Artifact_x0020_Link'},
drlItemLink: {dataFunc:function(objItem){return 'View DRL'}}
},
queryOrderby: 'Title';
})
.then(findSelectedItems(arrData, items);
.catch(function(errMsg){console.error(errMsg) });
}
function findSelectedItems(spData, selectedItems){
var emailBody = '';
for(var i = 0; i < selectedItems.length; i++){
var itemID = selectedItems[i].id;
for(var j = 0; j < spData.length; j++){
if (spData[i].iD == itemID){
emailBody += "Title: " + spData[i].drlId + "\r\n";
}
}
}
sendMail(emailBody);
}
function sendMail(bodyString) {
var message = encodeURIComponent(bodyString);
//var yourMessage = document.getElementById('AORNames');
var subject = document.getElementById('DRLID').value;
var emails = document.getElementById('AOREMails').value;
var mail = "mailto:" + emails + "?subject=" + subject + "&body=" + message;
window.location.href = mail;
}
</script>
</body>
Just before your function clickMethod you are missing a starting <script> tag. That's why it says malformed start tag. It's missing. Hope that helps.

How to create a button to add URL links in the form

Does anyone know how to add like a link button into a form? For example, a user clicks a + button and they can add an URL. They can add another URL if they wish and remove any links if required. Would be good to have validation for links as well.
I know for validation of the URL I can use "Check if a JavaScript string is a URL", but will need something that will validate all links if multiple have been added.
The best way to explain what I am trying to do is by looking at "Can I insert a hyperlink in my form?" in the form builder.
I just want to add links, and I don't need to display text or anything like that.
Is this what are you looking for?
Your question is a bit unclear.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
let i = 0;
let ii = 0;
function isURL(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
function removeLink(id, iid) {
console.log(id);
console.log(iid);
$(id).remove();
$(iid).remove();
return false;
}
function addLink(id) {
var input = prompt("Enter the link", "https://www.example.com");
var valid = isURL(input);
console.log(valid);
if(valid) {
var element = '<br><a id="_' + i + '" href="' + input + '">Link</a>';
console.log(element);
$(id).append(element);
let d = "'#_" + i + "'";
let dd = "'#__" + ii + "'";
let elment = ' <button type="button" id="__' + ii + '" onclick="removeLink(' + d + ', ' + dd + ')">Remove it!</button>';
$(id).append(elment);
console.log(elment);
i = i + 1;
ii = ii + 1;
}
else {
alert("The URL that you have entred is wrong.");
}
return false;
}
</script>
</head>
<body>
<form id="_form" method="POST">
<button type="button" onclick="addLink('#_form')">Add link</button>
</form>
</body>
</html>
Try it here: https://codepen.io/marchmello/pen/ZEGjMyR?editors=1000
What about DOM - not using longer form, so using URL as link text too.
function addUrl(e) {
var f = e.form;
var a = document.createElement("A");
a.href = e.value; // link URL
a.textContent = e.value; // link text
f.appendChild(a);
var x = document.createElement("INPUT");
x.type = "button";
x.value = "X";
x.onclick = remove;
f.appendChild(x);
f.appendChild(document.createElement("BR"));
}
function remove() {
var el = this, // button
parent = el.parentNode, // a must for remove
a = el.previousElementSibling; // anchor
if(el.nextSibling.tagName == 'BR') parent.removeChild(el.nextSibling);
parent.removeChild(el);
parent.removeChild(a);
}
<form>
<input name="url" size="50">
<input type="button" value="Add" onclick="addUrl(this.form.url)"><br>
</form>

CORS ERROR: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed

I am learning to use the "Article Search API" provided by the New York Times to allow my web application to display news articles based on the search results. I followed the tutorial at https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs and used their javascript code as closely as I could. The issue is that when I clicked on the 'submit search' button, my web-developer's console on Firefox showed me the message:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json?api-key=(MY KEY: CENSORED)&page=0&q=Trump&fq=document_type:(%22article%22)&begin_date=2019-01-01&end_date=2019-01-05. (Reason: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed)."
This is where I am getting stuck. I really do not know what is happening here.
The 'Article Search API' is currently using the base URL 'https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json', which I did carefully examine. I do not think the base-url has any problem, as can be conjectured based on the error message I got. I also tried to run this on Chrome and was using the Python testing server, but the problem remains.
I am willing to show the entire html file including the javascript.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>NY Times API example</title>
<link href="nytimes.css" rel="stylesheet">
</head>
<body>
<h1>NY Times video search</h1>
<div class="wrapper">
<div class="controls">
<form>
<p>
<label for="search">Enter a SINGLE search term (required): </label>
<input type="text" id="search" class="search" required>
</p>
<p>
<label for="start-date">Enter a start date (format YYYYMMDD): </label>
<input type="date" id="start-date" class="start-date" pattern="[0-9]{8}">
</p>
<p>
<label for="end-date">Enter an end date (format YYYYMMDD): </label>
<input type="date" id="end-date" class="end-date" pattern="[0-9]{8}">
</p>
<p>
<button class="submit">Submit search</button>
</p>
</form>
</div>
<div class="results">
<nav>
<button class="prev">Previous 10</button>
<button class="next">Next 10</button>
</nav>
<section>
</section>
</div>
</div>
<script>
// Defining a baseURL and key to as part of the request URL
var baseURL = 'https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json';
var key = 'CENSORED';
var url;
// Grab references to all the DOM elements you'll need to manipulate
var searchTerm = document.querySelector('.search');
var startDate = document.querySelector('.start-date');
var endDate = document.querySelector('.end-date');
var searchForm = document.querySelector('form');
var submitBtn = document.querySelector('.submit');
var nextBtn = document.querySelector('.next');
var previousBtn = document.querySelector('.prev');
var section = document.querySelector('section');
var nav = document.querySelector('nav');
// Hide the "Previous"/"Next" navigation to begin with, as we don't need it immediately
nav.style.display = 'none';
// define the initial page number and status of the navigation being displayed
var pageNumber = 0;
var displayNav = false;
// Event listeners to control the functionality
searchForm.addEventListener('submit', submitSearch);
function submitSearch(e) {
pageNumber = 0;
fetchResults(e);
}
function fetchResults(e) {
// Use preventDefault() to stop the form from submitting:
e.preventDefault();
// Assemble the full URL:
url = baseURL + '?api-key=' + key + '&page=' + pageNumber + '&q=' + searchTerm.value + '&fq=document_type:("article")';
if (startDate.value !== '') {
url += '&begin_date=' + startDate.value;
}
if (endDate.value !== '') {
url += '&end_date=' + endDate.value;
}
// Use fetch() to make the request to the API
fetch(url).then(function(result) {
return result.json();
}).then(function(json) {
displayResults(json);
});
}
function displayResults(json) {
while (section.firstChild) {
section.removeChild(section.firstChild);
}
var articles = json.response.docs;
if(articles.length === 10) {
nav.style.display = 'block';
} else {
nav.style.display = 'none';
}
if(articles.length === 0) {
var para = document.createElement('p');
para.textContent = 'No results returned.'
section.appendChild(para);
} else {
for(var i = 0; i < articles.length; i++) {
var article = document.createElement('article');
var heading = document.createElement('h2');
var link = document.createElement('a');
var img = document.createElement('img');
var para1 = document.createElement('p');
var para2 = document.createElement('p');
var clearfix = document.createElement('div');
var current = articles[i];
console.log(current);
link.href = current.web_url;
link.textContent = current.headline.main;
para1.textContent = current.snippet;
para2.textContent = 'Keywords: ';
for(var j = 0; j < current.keywords.length; j++) {
var span = document.createElement('span');
span.textContent += current.keywords[j].value + ' ';
para2.appendChild(span);
}
if(current.multimedia.length > 0) {
img.src = 'http://www.nytimes.com/' + current.multimedia[0].url;
img.alt = current.headline.main;
}
clearfix.setAttribute('class','clearfix');
article.appendChild(heading);
heading.appendChild(link);
article.appendChild(img);
article.appendChild(para1);
article.appendChild(para2);
article.appendChild(clearfix);
section.appendChild(article);
}
}
};
</script>
</body>
</html>
But I think the most important lines are as follows:
var baseURL = 'https://nyt-prod.apigee.net/svc/search/v2/articlesearch.json';
var key = 'CENSORED';
...
...
url = baseURL + '?api-key=' + key + '&page=' + pageNumber + '&q=' + searchTerm.value + '&fq=document_type:("article")';
...
...
fetch(url).then(function(result) {
return result.json();
}).then(function(json) {
displayResults(json);
});
...
...
if(current.multimedia.length > 0) {
img.src = 'http://www.nytimes.com/' + current.multimedia[0].url;
img.alt = current.headline.main;
}
The news articles are supposed to show up on the right hand side in blocks arranged in a vertical fashion. With this error, I saw nothing. I hope someone can help me.

Javascript cookie not saving when user input reaches a certain size

I am trying to Save user input from a textarea in a javascript cookie on the unload of a page and then read it back into a textarea when the user returns. The issue that I am having is the cookie is not saving when the user input reaches a certain length. It seems to be working fine with small strings.
Here is the html:
<html>
<head>
<title>Cookie Test</title>
<link rel="stylesheet" type="text/css" href="css/site.css">
</head>
<body class="full" onload="GetCookies()" onunload="WriteCookies()">
<div class="fullscreen-overlay" id="fullscreen_overlay">
<div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
<textarea name="fullscreen-contents" id="fullscreen-contents"></textarea>
</div>
</div>
</div>
</body>
</html>
Javascript:
function WriteCookies() {
var d = new Date();
var n = document.getElementById('fullscreen-contents').value;
d.setDate(d.getDate() + 1);
document.cookie = "mainCookie = " + n + "; expires = " + d.toGMTString() + "";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function GetCookies() {
document.getElementById('fullscreen-contents').value = getCookie('mainCookie');
}
Any ideas what could be going on? Thanks!
The max size of a cookie is 4093 bytes. Perhaps the long string is just eclipsing that limit. You could consider localStorage or sessionStorage instead
var text = document.getElementById('fullscreen-contents');
function saveText() {
localStorage.savedText = text.value;
console.log("saved");
}
function getText() {
if (localStorage.savedText) {
text.value = localStorage.savedText;
console.log("loaded");
}
}
Edited: Here is a fiddle

Don't show this page anymore (JQUERY cookie)

I'm trying to implement cookies for my website, i just wanted to redirect users to a splash page and have a "remember me" checkbox there and once they checked off that and pressed enter, they will not see that page anymore.
So using COOKIE Plugin I can set a cookie for users and redirect them to the page, but I wasn't able to implement how to detect the remember me box..
$(function() {
var COOKIE_NAME = 'splash-page-cookie';
$go = $.cookie(COOKIE_NAME);
if ($go == null) {
$.cookie(COOKIE_NAME, 'test', { path: '/', expires: 6 });
window.location = "/splash.php"
}
else {
}
});
Anybody has done like this before? Or anybody have any similar idea to implement this?
Any help would be appreciated.
Solution #1 (With alert boxes): I came up with this but without the COOKIE Plugin. Hopefully you can get some use out of this. Mostly Pure JS with some JQuery to fancy it up a little.
Here is the DEMO.
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('#remember').click(function() {
if (this.checked) {
$('#x').text("You're the Best!");
setCookie();
} else {
$('#x').text("Come on, You know you want to!");
}
});
});
function setCookie() {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
addCookie("username", user, 30);
}
}
function addCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
//window.location.href = "https://www.google.com"; // redirect after the prompt
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
window.location.href = "https://www.google.com";
}
}
function goTo() {
window.location.href = "https://www.google.com";
}
</script>
</head>
<body onLoad="checkCookie();">
<h1>Splash Page</h1>
<form>
<input type="checkbox" id="remember"> Remember me
<br>
<input type="button" value="Enter" onClick="goTo();">
</form>
<p><div id='x'></div></p>
</body>
</html>
Solution #2 (NO alert boxes): I came up with this as a second simplified solution by request which is more compatible with mobile (Chrome, etc.). Hopefully you can get some use out of this. Mostly Pure JS with some JQuery to fancy it up a little.
Here is the DEMO.
Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<!-- JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('#remember').click(function() {
if (this.checked) {
$('#x').text("You're the Best!!!");
addCookie(30);
} else {
$('#x').text("Come on, You know you want to!");
deleteAllCookies();
}
});
});
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
function addCookie(exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = expires;
}
function checkCookie() {
if (document.cookie == false) {
//alert("Welcome New User");
} else if (document.cookie.indexOf("expires") >= 0) {
//alert("Welcome Back");
window.location.href = "https://www.google.com";
}
}
function goTo() {
window.location.href = "https://www.google.com";
}
</script>
</head>
<body onLoad="checkCookie();">
<h1>Splash Page</h1>
<form>
<input type="checkbox" id="remember"> Remember me
<br>
<input type="button" value="Enter" onClick="goTo();">
</form>
<p><div id='x'></div></p>
</body>
</html>

Categories