radio buttons and cookie settings - cookies

I don't know anything about cookies or how to set them and I need some advice. I have two radio buttons. For example if an option is changed from one to another, that option will remain even if the page is refreshed or changed on other pages where this radio buttons exist, and I need to make the cookie setting for this code. Can someone can give me some advice regarding what code should I add to my php?
This is js code:
$(document).ready(function() {
$('radio[name=radio]').each(function() {
$(this).click(function() {
my_function();
});
});
});
my_function()
{
var value_checked = $("input[name='radio']:checked").val();
$.ajax({
type: 'POST',
url: 'page.php',
data: {'value_checked':value_checked},
});
}
html code
<form>
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" /><label for="radio2">Choice 2</label>
</div>
</form>

It is important to remember that cookies can only be set before any output is sent to the client on a webpage, because cookies are set as headers, and headers can only be sent prior to any part of the webpage output. Therefore, you need to refresh the page to set a cookie to the value of your radio button.
At the very top of the php, BEFORE the <!DOCTYPE> html or <html> tag, you need to add something like this:
<?php
if(isset($_POST['radio1'])) {
setcookie('radio1', true, 600, '/');
setcookie('radio2', false, 600, '/');
} else if(isset($_POST['radio2'])) {
setcookie('radio2', true, 600, '/');
setcookie('radio1', false, 600, '/');
}
?>
The above code will make sure that only one of the cookies is set to true and the other is set to false. The cookies will expire after ten minutes.
This is after you properly set up the html form so that you can detect that your user has selected a button:
<form method="POST" action="index.php">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" />
<label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" />
<label for="radio2">Choice 2</label>
</div>
</form>
The PHP Manual page has more information: http://php.net/manual/en/function.setcookie.php
EDIT: Semantic code changes and fixed the html tags described.

See setcookie examples how to set cookies in PHP. But you can do it also with javascript js_cookies.

Related

Displaying a text field along with radio through Django form

Lets say I have a model with 2 fields. With one field being a choice field of radio button Choice1, Choice2 and Other, the next being Other which is a textfield I want the "other" textbox to appar / enabled only when "Other" is selected in the radio button.
This question is not from the django-forms category. This applies more to the front-end category. Everything that is sent from the django server is static. Sure, you can write a form class and override the template for it. Also, you can connect the js script directly to the form class. It is convenient, but not canonical. Just, write the JS script or using JQuery, which will activate the field when you select a particular option.
I wrote for you a small example of how this can be do it.
I hope this helps you.
$('input[type=radio][name=choices]').change(function() {
$('input[type=text][name=other]').prop(
'disabled',
function(i, v) {
return !v;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p><input name="choices" type="radio" value="choice1">Choice 1</p>
<p><input name="choices" type="radio" value="choice2">Choice 2</p>
<p><input name="other" type="text" disabled></p>
</form>

How to use django-markdownx in my view in similar way to admin?

I'm stuck using django-markdownx to automatically update page and to submit changes.
I followed this question and answer and managed to get django-markdownx working in admin, and within my view. However in my view editing the textarea does not automatically update the page.
The admin page with django-markdownx is exactly what I want, updating the textarea updates the page, but not the underlying database field until you hit save.
So I then tried to rip out the admin code into my own view.
In my view/template I have a form, textarea similar to admin one. I also included "/static/markdownx/js/markdownx.js" and set my form to mostly be similar to the admin page:
<form method="POST" action="">{% csrf_token %}
<div class="markdownx">
<textarea name="myfield" rows="10" cols="40" required="" data-markdownx-upload-urls-path="/markdownx/upload/" data-markdownx-editor-resizable="" class="markdownx-editor" id="id_myfield" data-markdownx-urls-path="/markdownx/markdownify/" data-markdownx-latency="500" data-markdownx-init="" style="transition: opacity 1s ease;">
{{ note.myfield }}
</textarea>
</div>
<div class="markdownx-preview">
{{ note.formatted_markdown|safe }}
</div>
</form>
This didn't work.
I see periodically there is requests to /markdownx/markdownify/ when you edit in admin, but not mine. I'm not sure if I should aim to do the same or just do some timed javascript page refresh and pass all the data from within my form back to my view to then re-render the page again.
I can't quite get my head around the django-markdownx documentation.
UPDATE:
The Documentation seems to suggest that a call to MarkdownX() should do the initialisation.
<script src="/static/markdownx/js/markdownx.js"></script>
...
<script type="text/javascript">
let parent = document.getElementsByClassName('markdownx');
let md = new MarkdownX( element, element.querySelector('.markdownx-editor'), element.querySelector('.markdownx-preview'));
</script>
But when I try this I get.
Uncaught ReferenceError: MarkdownX is not defined
Also I don't see any initialisation like this within the admin page.
Is there an example of using the django-markdownx in your own views similar to the usage within admin?
Thanks
LB
The following is a broken solution.
The correct method would be to use the MarkdownX's built-in Javascript, but I just can't get it to work, yet. So, I wrote my own. It may be of use to others.
In template html, include js.cookie.min.js in order to get the django csrftoken. Then a callback function which will be called when a change is made to the textarea. We then update the preview div with HTML code we received back from MarkdownX's markdownify call.
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
...
<script type="text/javascript">
function myMDFunc( elem ) {
input = elem.value;
var csrftoken = Cookies.get('csrftoken');
$.ajax(
{
type: "POST",
url: "/markdownx/markdownify/",
data: { CSRF: csrftoken, csrfmiddlewaretoken: csrftoken, content: input}
})
.done(function(data, status){
document.getElementById("markdownx-preview").innerHTML = data;
});
}
</script>
Still in the template html, in the form, call this function both for onchange and onkeyup.
<form method="POST" action=""> {% csrf_token %}
{{ note.title }}
<div class="markdownx">
<textarea onchange="myMDFunc(this)" onkeyup="myMDFunc(this)" cols="60" rows="5" name="text" >
{{ note.myfield }}
</textarea>
</div>
<div class="markdownx-preview" id="markdownx-preview">
{{ note.formatted_markdown|safe }}
</div>
<input type="submit" id="submit" name="submit">
</form>
In summary, a change to the textarea means we invoke the 'onchange' or 'onkeyup', which calls myMDFunc. Then myMDFunc does an ajax call with data which is the raw MarkDown code, the response to this call is the pretty HTML data. The callback within myMDFunc updates the preview with that pretty HTML.
It kinda works. I'm sure the real MarkdownX code will handle drag'n'drop of images and pacing the ajax calls to be nice to the server.

Fancybox to open on link click only first time then go to page url

I'm trying to gate a link using fancybox and cookies to show a form the first time the link is clicked and then once the form is submitted the popup form would no longer pop up but instead would open to the page url. Here is my code but so far all I can do is get the popup form to show on link click. How do I tell fancybox to not show if the cookie is present and instead go to a page link?
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
<link href="http://intercross2.com/CPS_landing_page/assets/fancybox/dist/jquery.fancybox.min.css" rel="stylesheet" />
</head>
<body>
<a class="fancybox" data-fancybox data-src="#donation-info" href="thankyou.html" alt="">Fancybox</a>
<div style="display:none">
<div id="donation-info">
<h2>Answer a few short questions to continue</h2>
<form id="gate" method="post" action="sendmail.php">
<label for="name">Your Name</label><br>
<input type="text" name="name" title="Enter your name" class="required"><br>
<label for="phone">Daytime Phone</label><br>
<input type="tel" name="phone" class="required"><br>
<label for="email">Email</label><br>
<input type="email" name="email" title="Enter your e-mail address" class="required email"><br>
<input type="submit" name="submit" class="submit-link" id="submit" value="Submit" />
</form>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script src="http://intercross2.com/CPS_landing_page/assets/fancybox/dist/jquery.fancybox.min.js"></script>
<script>
$(function () {
// Define cookie name
var cookieName = 'hide_form';
// Configure fancyBox
$('.fancybox').fancybox({
autoDimensions: false,
autoSize: false,
height: 'auto',
padding: 20,
width: 650,
afterClose: function() {
// Set cookie to hide fancybox for 1 day
$.cookie(cookieName, true, { expires: 1 });
}
});
// Handle submit click event
$('a#submit').on('click', function (event) {
event.preventDefault();
// Hide fancybox and set cookie to hide fancy box for 7 days
$.fancybox.close();
$.cookie(cookieName, true, { expires: 7 });
});
</script>
</body>
</html>
If you need to do check if cookie exists, then use something like:
if (!!$.cookie(cookieName)) { /* Open fancyBox here */ }
The rest is up to you.

create a html form with 2 action pags

How can i create a html form that action attribute have 2 destination.I want when user click on submit bottom , check if user entered wrong data the page goes to another pages with window.location and if user insert the correct input goes to main page with the same instruction.
First of all, what do you mean by correct input?
Main form data validation occurs in server side, not client side. you'd better use client side just for simple verification, like for typos.
There is no need for 2 destination pages (as you call it so).
You may use the standard action attribute which is the page on the server to which you are sending your form data.
there, You have the option to decide which condition needs what action and send the data (and then the user) to the desired page / action.
Sample code for the form
<form id='myform' action='action.php' method='POST' target='formresponse'>
<label for='name' >Your Full Name*: </label><br/>
<input type='text' name='name' id='name' maxlength="50" /><br/>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' maxlength="50" /><br/>
<input type='button' name='Submit' value='Submit' />
</form>
<iframe name='formresponse' width='300' height='200'></frame>
Multiple action
function SubmitForm()
{
document.forms['contactus'].action='action1.php';
document.forms['contactus'].target='frame_result1';
document.forms['contactus'].submit();
document.forms['contactus'].action='action2.php';
document.forms['contactus'].target='frame_result2';
document.forms['contactus'].submit();
return true;
}

Meteor with i18next cookies

I have a simple login page with a "option" for select language :
<input type="text" class="form-control" id="identifiant" data-i18n="[placeholder]login.placeholders.username" autofocus>
<input type="password" class="form-control" id="password" data-i18n="[placeholder]login.placeholders.password">
<input id="loginCheckbox" type="checkbox" value="remember-me"/> <label for="loginCheckbox" data-i18n="login.rememberme"></label>
<br>
<center>
<div class="form-group col-lg-6 col-lg-offset-3">
<select id="select-lang" class="form-control">
<option value="en-US" data-i18n="lang.english"></option>
<option value="fr-FR" data-i18n="lang.french"></option>
</select>
</div>
The JS part :
if(Meteor.isClient) {
Meteor.startup(function() {
i18n
.init({
fallbackLng:'en-US',
})
.done(function() {
$('[data-i18n]').i18n();
});
});
}
When you change the language on the login page everything work perfectly :). But when I log a user, I lost the translation for other pages. My question is : How can I save the language setting for all my site ? Cookies ?
Sorry, I'm new with i18next :)
Yep, cookies are the way to go. Session is not enough since it's not persistent.
Cookie.set('lang', 'en-US');
Cookie.get('lang');
Use Meteor Session.
if(Meteor.isClient) {
Meteor.startup(function() {
if(typeof Session.get('lang') == 'undefined') {
//set default lang
Session.set('lang', 'en-US');
}
i18n
.init({
fallbackLng: Session.get('lang'),
})
.done(function() {
$('[data-i18n]').i18n();
});
});
And change the Session when changing language.
Session is active until user closes his browser. If you want to preserve chosen language after re-opening browser store the lang in collection.