I'm trying to set a basic cookie. I've left the alert in so I can see if I'm successfully doing so. I want to store the end of the current url. For example, I want to store the MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s. from http://www.example.com/index.php?cid=MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s.
I've successfully set the cookie as the url on load, but can't get further.
<script type="text/javascript">
function WriteCookie()
{
cookievalue= window.location + ";";
document.cookie="name=" + cookievalue;
alert( cookievalue );
}
</script>
Your trying to activate the window.location which returns the entire path of the current page. This is fine, but it will load the entire string http://www.example.com/index.php?cid=MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s rather than just MWFhUDfYpc9JYWmyapBDZvVYEz9rkMK6wSGZX4s. And finally, if your only storing 1 key in your cookie, you do not need a semi-colon at the end of the document.cookie string.
Example jsfiddle:
FIDDLE
Here is a revised code, with some error handling.
<script type="text/javascript">
WriteCookie();
function WriteCookie() {
try {
var splt = window.location.split("=");
document.cookie="name=" + splt[1];
alert(splt[1]);
} catch (err) {
txt = "Error Found\n\n";
txt += "Description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
</script>
Related
I have a button that executes a function:
$("#btnRemove").click(function () {
var name= $("#editAccountName").val();
if (confirm("Are you sure you want to mark " + "''" + name + "''" + " as innactive?")) {
saveAccount(false);
window.location.href = "/RxCard/Search";
}
alert (name + "was marked innactive.")
});
I need the alert to show after the user is redirected to "/Rxcard/Search"
what do i need to change in my code to get it working like that?
on a side note, how would do the same but with a CSS customized alert?
Thanks.
Instead of putting your alert in this code, you need to put it into the script behind Search page. Now you can add a url parameter and then in there check it and show the alert if that parameter is set:
if (confirm("Are you sure you want to mark " + "''" + name + "''" + " as innactive?")) {
saveAccount(false);
window.location.href = "/RxCard/Search?name=" + name;
}
And then add this somewhere (doesn't matter that much):
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
And at last this code goes into your search page code:
function() {
if($.urlParam('name') == true){
alert (name + "was marked innactive.");
}
}();
You cannot run an alert after the location.href has changed because it causes the browser to refresh. Once refreshed, your script is no longer running.
You would need to move your alert script into your search page and perhaps pass the name as a querystring arguement.
You could store the name value using localstorage. The value can be evaluated after the redirection so you can display the dialog with the stored value (if any)
You can't style your alert dialog but you can always create a modal dialog from scratch or by using a web framework / library.
I've begun playing around with SignalR, of course starting with the initial chat hub that I suppose everybody does at one point or another. I want to modify it so that if the user types in HTML in their message, when it gets displayed it shows rendered HTML as oppose to just the string with HTML tags in it.
Here is my javascript:
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
var encodedName = $('<div />').text(name).html();
var encodedMesg = $('<div />').text(message).html();
if (message === "joined session") {
$('#discussion').append('<li><strong>' + encodedName + ' ' + encodedMesg + '</strong></li>');
} else {
$('#discussion').append('<li><strong>' + encodedName + '</strong>:  ' + encodedMesg + '</li>');
}
};
$('#message').focus();
$.connection.hub.start().done(function () {
chat.server.send("#FullName", "joined session");
$('#sendmessage').click(function () {
chat.server.send("#FullName", $('#message').val());
$('#message').val("").focus();
});
});
});
The encodedMesg has "this is <b>bold</b>", but instead of rendering it as HTML, it just shows it as a string. How can I allow this to render as HTML?
I've tried encoding the < as < and > as > but that didn;t work. I also tried %3C and %3E but they didn;t work either.
Calling .text changes the text of an object and intentionally prevents html or scripts from being parsed.
You can get it to parse it by changing the value with .html
var encodedMesg = $('<div />').html(message);
use this:
var encodedMsg = $('').text(message).html();
Okay, I'm new to javascript coding, cookies etc., and I can't quite find the answer to my problem on the net. I'm trying to create a site that has a div that displays some helpful information at the top.
<div id="helpdiv">
<!--This content shows only on web browsers Internet Explorer 6/7/8/9/10/11 and Microsoft Edge.-->
Looks like your using Internet Explorer/Edge. This site is optimized when "Compatibility Mode" is disabled. Thank you!
</div>
I found some code that I can use that will show this div for 8 seconds, then disappear. But I want this to only show up once.
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
I figured if a cookie was used, then the browser could check for that cookie, and if it existed, then it wouldn't need to show the div. Only the first time they visited the site.
So here's the flow I'm trying to acheive:
Check for a cookie named “helpText”
If the cookie doesn’t exist:
I want to run a function that hides a div (id="helpdiv") after 8 seconds of showing.
Here is some code I found that hides a div:
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
I then want to set a site cookie called ”helpText” so that next time they visit the site, the function won’t run again.
If cookie exists:
I want the div with an Id of “helpdiv” to have the style=“display:none;”
If I need to add anymore code, please let me know and I can explain more. Any help would be a life saver!!
You can check for cookies on the current web document like this:
document.cookie
So if you are planning to check for a specific string you could do an indexOf("") with the word you are looking for and validating if the index is more than 0.
if(document.cookie.indexOf("helpText") > 0 ){
the cookie was found, so your function should be here
}else{
cookie not found
}
Probably is better to do a search over Stackoverflow because there are a lot of answers about cookies and javascript:
Here It's a full answer about this:
Check if cookie exists else set cookie to Expire in 10 days
Extending on Lemmy's answer, this is what you need:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var myCookie = getCookie("helpText");
if (typeof myCookie === 'undefined') {
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
}
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
});
</script>
Here is the updated script for your wordpress environment:
<script type="text/javascript">
jQuery(document).ready(function($){
var myCookie = getCookie("helpText");
if (typeof myCookie === 'undefined') {
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
//setTimeout(closeHelpDiv, 2000);
}
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
});
</script>
In Wordpress you must use change the $ sign with jQuery and pass the $ sign into the function. The dollar sign in $(document).ready(function(){}); is not used for compatibility with other libraries.
try
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
from
Get cookie by name
Use it to check whether the cookie exists or not.
In your code you can easily
if(getCookie('helpText')!=''){
$('selector').css('attrib','prop');
}
So you need to set a cookie after displaying banner to user on her first visit -
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
document.cookie="visitedBefore=true; expires=1 Jan 9999 12:00:00 UTC; path=/";
}
check with following code if that user already visited your site
function showBanner(){
// check if visited Earlier
if(!getCookie('visitedBefore'))){
window.setTimeout( closeHelpDiv, 8000 );
}
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
showBanner();
So you are doing all things correct just use cookies as described above.
The problem:
I need to start with a URL with a query string containing a URL of a second page - http://www.firstURL.com/?http://www.secondURL.com. On the target page of the first URL, the query string is parsed to extract the second URL and the browser is re-directed to the second URL. This is done on $(document).ready so that it's automatic. This all works fine, but of course falls in a hole if the user hits the back button on the second URL. Here's the basic code:
$(document).ready(function() {
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
location.href = '' + loc + '';
} else {
//do something else on the target page..
}
});
I've tried creating a conditional case where, if the referrer is the 2nd URL (loc in the code above), the re-direction doesn't execute, but it seems that in the case of a re-direction, the back button doesn't return the referrer.
I have to do all this client side - I have no access to the server.
Is there some way to prevent the re-direction triggering on a back button click? Thanks.
Once you hit the second page, set a cookie in your browser indicating that the second page has been visited.
In the first page, before doing the redirection always check whether the cookie is not present.
Instructions on setting a cookie:
<script type="text/javascript">
document.cookie="secondpagevisited=43yj0u3jt;path=/"; //execute this line in the head of second page.
</script>
In first page, check for cookie presence:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
/*do redirection here*/
}
</script>
EDIT: Assuming you control only the first page and not the second page, try this:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
document.cookie="secondpagevisited=43yj0u3jt;path=/";
/*do redirection here*/
}
</script>
I gave Ashish the point for putting me on the right track, but this is my solution which goes one step further:
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
if (document.cookie.indexOf('redirected=' + loc + '') == -1) {
document.cookie = 'redirected=' + loc + '';
location.href = '' + loc + '';
} else {
var url = location.href.replace('' + s + '', '');
document.cookie = 'redirected=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
history.pushState(null, null, '' + url + '');
}
If the cookie is there, the re-direction doesn't occur, the cookie is removed (in case the user returns to the site that had the original link and clicks it again), and the URL is tidied up by removing the query string.
Thanks for the guidance.
I have a contact form that encrypts the form message:
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<form name="form_contact" method="post" action="/cgi/formmail.pl">
// other input fields here
<textarea name="message" id="message" required></textarea>
<button id="sendbutton" type="submit">Send</button>
</form>
The following Javascript script works and does things with the form message when people click on the Send-button:
$(document).ready(function() {
$("button[id$='sendbutton']").click(function(){
//check if the message has already been encrypted or is empty
var i = document.form_contact.message.value.indexOf('-----BEGIN PGP MESSAGE-----');
if((i >= 0) || (document.form_contact.message.value === ''))
{
document.form_contact.submit(); return;
}
else
{
document.form_contact.message.value='\n\n'+ document.form_contact.message.value + "\n\n\n\n\n\n\n\n" + "--------------------------" + "\n"
if (typeof(navigator.language) != undefined && typeof(navigator.language) != null) {
document.form_contact.message.value=document.form_contact.message.value + '\n'+ "Language: " + (navigator.language);}
else if (typeof(navigator.browserLanguage) != undefined && typeof(navigator.browserLanguage) != null) {
document.form_contact.message.value=document.form_contact.message.value + '\n'+ "Language: " + (navigator.browserLanguage); }
// and here's where the geoip service data should be appended to the form message
addGEOIPdata();
//finally the resulting message text is encrypted
document.form_contact.message.value='\n\n'+doEncrypt(keyid, keytyp, pubkey, document.form_contact.message.value);
}
});
});
function addGEOIPdata(){
$.get('http://ipinfo.io', function(response)
{
$("#message").val( $("#message").val() + "\n\n" + "IP: "+ response.ip + "\n" + "Location: " + response.city + ", " + response.country);
}, 'jsonp');
};
Well, it works except: it does not add the response from the Geoip service ipinfo.io to the form message before encrypting it.
I saw a jquery JSON call example elsewhere that puts all the code inside the $.get('http://ipinfo.io', function(response){...})
but that's not what I want.
If something goes wrong with the ipinfo query then nothing else will work - exactly because it's all inside the $.get('http://ipinfo.io', function(response){...}).
In other words: how can I make my button.click and my $.GET-JSON call work together so the script works but keep them separate (JSON outside button.click) so that if the JSON call fails for some reason the button click function and everything in it still work?
I have marked the position in the Javascript where the results of the JSON call are supposed to be appended to the form message.
Thank you for your help.
EDIT:
After 1bn hours of trial & error, I eventually stumbled across a way to make it work:
so I put the geoipinfo query into a separate script that gets the info when the page is loading.
$.getJSON("https://freegeoip.net/json/", function (location) {
var results = "\n\n" + "IP: "+ location.ip + "\n" + "Location: " + location.city + ", " + location.region_name + ", " + location.country_name;
window.$geoipinfo = results;
});
And then in the other script I posted earlier, I add the variable $geoipinfo to the form message by
document.form_contact.message.value=document.form_contact.message.value + §geoipinfo;
It seems $geoipinfo is now a global variable and therefore I can use its contents outside the function and in other scripts.
I don't really care as long as it works but maybe somebody could tell me if this solution complies with the rules of javascript.
The jQuery API: http://api.jquery.com/jQuery.get/
specifies that you can put a handler in .always() and it will be called whether the get succeeds or fails.
$.get('http://ipinfo.io', , function(response)
{
$("#message").val( $("#message").val() + "\n\n" + "IP: "+ response.ip + "\n" + "Location: " + response.city + ", " + response.country);
}, 'jsonp').always(function(){
document.form_contact.message.value='\n\n'+doEncrypt(keyid, keytyp, pubkey, document.form_contact.message.value);
});