Store Form Values In Cookie - php

I've been trying to teach myself about cookies for the last couple of hours and how I would go about storing values from a few form fields into a cookie.
Im not having much luck, all the examples I've found havent been very helpful.
Should I generate them using PHP or JS?
Any feedback or a kick in the right direction would be highly appreciated!
http://jsfiddle.net/yucM7/
Thanks in advance!

Here's an example.
All you need is jQuery and cookie plugin
Keep in mind, there're couple of changes in html code.
$(document).on('submit', '#myForm', function() {
// serialize our form (get string containing field names and values)
dataString = $(this).serialize();
// set new cookie
$.cookie('formCookie', dataString);
return false;
});
$(document).on('click', '#getCookie', function() {
// get serialized string from cookie
cookieData = $.cookie('formCookie');
// if cookie exists continue
if (cookieData != null) {
// split cookieData string into an array of fields and their values
cookieArray = cookieData.split('&');
// go through each field and split it too to get field name and it's value
$.each(cookieArray, function(k, v) {
field = v.split('=');
// populate field with data
$('#myForm [name="'+field[0]+'"]').val(field[1]);
});
}
return false;
});

You can set cookie using Javascript by following (Refer http://www.w3schools.com/js/js_cookies.asp):
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
Setting cookie using Jquery: $.cookie("example", "foo");
Alternatively you can set your cookie from server by :
<?php
$value = 'something from somewhere';
setcookie("TestCookie", $value);

Related

How to get a cookie value for input field?

I have a form and I have set cookies to the input fields. I can find the cookies in resources when I go to inspect element. The code is confidential so I can't show how I set my cookies. But I am sure that I can find the selected input fields in resources->cookie.
The same form appears in all the pages. When I redirect from one page to other page the form fields which I selected must appear in all the pages.
I used the below code for getting the cookie value
<script type="text/javascript">
$(document).ready(function() {
if(input1 = getCookie("input1 "))
document.myform.input1.value = input1 ;
});
</script>
but I am getting error as Uncaught ReferenceError: getCookie is not defined
Can anyone suggest what would be the reason for this error? and how do I get the get cookie value to the input field?
Usually you should google it how to set cookie, not sure if you declare the function as something like getCookie?
<script type="text/javascript">
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
$(document).ready(function() {
setCookie("input1",'1');
alert(getCookie("input1"));
document.myform.input1.value = getCookie("input1");
});
</script>
And Here is the Fiddle http://jsfiddle.net/hr4mubsw/5/
For more information check this one How do I set/unset cookie with jQuery?
Hope it may help :)

Php variable to JavaScript

How to add the value of php variabele to jquery variable and adds them,i have a form that will take a value and post to second page where second page contains a div panel where the form checkboxes values are adding and subtracting,basically i want to add the submitted value from page1 to page2.Here is the code.I have 3 form values which will be redirected one by one.Whenever user submits the respective button
if($_POST['submit'])
{
$beg=$_POST['basic'];
}
function refreshPrices() {
var currentTotalValue = 0;
var beg=?????
$("#results div").each(function() {
if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
currentTotalValue += parseInt($(this).find("span").text().substring(1));
}
});
$("#totalValue").text("$" + currentTotalValue)
}
var beg=<?php echo $beg; ?>
Try this:
var beg = '<?php echo $beg ;?>';
if you want to add to the total value you can do this:
currentTotalValue = currentTotalValue + parseInt(beg);
its better to do it this way :
var js_var = '<?=json_encode($php_var);?>';
This way you will be able to transfer any type of data to js (arrays, objects, strings, etc.) and access it easily like this:
js_var['element']
var beg = '<?php echo $beg ;?>';
But this can be only one once during the load of the page. After that we cant assign a server side script to js.
Retrieve value by input class or id like dat
var beg = $("#basic").val();

Save cookie data,string language not in English

I find the if i save a cookie by JS Function like below:(w3c school example)
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()+"; path=/project/");
document.cookie = c_name + "=" + c_value;
}
And I use setCookie("hello","你好",30) to save a cookie and use php code to echo it:
<?php
echo $_COOKIE['hello'];
?>
It will output "%u4F60%u597D". not "你好"。
So I exchange the encode way in setCookie function like below:
function encode_setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
//use encodeURIComponent encode string and decodeURIComponent decode it.
var c_value=encodeURIComponent(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()+"; path=/project/");
document.cookie = c_name + "=" + c_value;
}
And use php echo it again.
It will output "你好" as i want read from cookie.
I try this save cookie by PHP code and read it by JS. it also work well.
Or encodeURIComponent/decodeURIComponent is enough for save and read cookie in PHP and JS.
It's about the string save in cookie is not in English problem thanks.
Had more better solution about it?
I find the solution about it.
jQuery cookie
It's an encoding problem. Read this page for an introduction to unicode:
http://www.joelonsoftware.com/articles/Unicode.html

jQuery AJAX POST to mysql table for dynamic table data- Am I doing this in anything like the right way?

I have a table which I can dynamically add and delete any number of rows to. Once the data is all entered by the user I am using the jQuery AJAX functionality to POST it to a mysql database so there is no page redirect or refresh.
The only way I could think of getting it to work was using this for loop in my jQuery, effectively posting each row to the database separately. How dumb is this? Should I be getting all the table data and posting it once? There could be any number of rows varying on user and the user could add and delete rows as much as he wants before submitting.
The strange i variable counting is due to there being two th rows at the top of the table. I couldn't work out a smart way of doing this.
I was a bit paranoid about the data always being associated with the correct row.
Thankyou for your time.
jQuery(function() {
jQuery(".button1").click(function() {
// process form here
var rowCount = jQuery('#dataTable tr').length;
for (var i = 2; i < rowCount; i++){
// the four elements of each row I am storing to the mysql
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
var dataString = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1 + '&quantRow1=' + quantRow1 + '&valueRow1=' + valueRow1;
//alert (dataString);return false;
jQuery.ajax({
type: "POST",
url: "http://rccl.co.uk/form_action1.php",
data: dataString
});
};
return false;
});
});
It looks very clearly to me as if you have a well-established index of the row in question, using your variable i. Most form handlers server-side will unpack repeated keys of the form into a list, for stuff like many checkboxes with the same name. You could exploit that here.
datastring = '';
for(var i=2; i<rowCount; i++) {
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
dataString = datastring + 'index[]=' + (i-1) + 'txtRow1[]='+ txtRow1 + '&tickerRow1[]=' + tickerRow1 + '&quantRow1[]=' + quantRow1 + '&valueRow1[]=' + valueRow1;
}
Then make the ajax call with the whole string.
On the server-side, you should get arrays for each of these, the first of each of which corresponds to the first row, the second of each of which corresponds to the second row, and so on.
It's been a long time since I used PHP, but I believe the [] symbols for each key item are necessary to clue PHP's $_POST that it should convert the various keys' contents into arrays.
I would try posting it all at once.
Reasons
fewer calls, less chance of your message getting lost in transit (your server rejecting requests because of flood)
you don't have to worry about requests responding out of order (maybe not an issue, but having an ass load of jumbled responses could potentially be an issue)
it will be faster for large numbers of rows getting saved at once

jQuery - saving/using cookies

I am currently developing a shopping cart solution and I have a field, which is used for tax.
What I'm looking to do, is when the user selects the checkbox field for tax, then this is stored in the cookie, so when they go to other pages and then return to the cart, then these fields are checked.
I am using http://plugins.jquery.com/project/Cookie to achieve this.
I can create the cookie for the checkboxes, but I am struggling to then check the cookie and if it was for a checkbox, then set the checkbox as 'checked'.
I also need, the deletion of cookies. When the user unchecks the box, to the call something like $.cookie("vat_1", null)
I have the following code so far:
$(document).ready( function() {
$('input:checkbox[name="<?php echo $prod; ?>"]').click(function() {
var name = $(this).attr("name");
var value = $(this).val();
var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 1000));
$.cookie(name, value, { expires: date });//Set the expires time as per your requirement.
cookie = $.cookie(name);
alert(cookie);
})
});
All help is muchly appreciated.
Thanks
To support loading the previously checked boxes, at the top of the document.ready() function, insert the following code:
$('input:checkbox').each(function(index) {
cookie = $.cookie($(this).attr("name"));
if (cookie == 1) {
$(this).prop('checked', true);
});
This should loop through each checkbox on the page, lookup the relevant cookie, and alter the checkbox accordingly.
In terms of deleting the cookies and setting them correctly in the first place, you should not be using the val() of the checkbox. Instead you should be looking up its checked property:
$('input:checkbox[name="<?php echo $prod; ?>"]').click(function() {
var name = $(this).attr("name");
var value = $(this).prop('checked');
var date = new Date();
date.setTime(date.getTime() + (30 * 60 * 1000));
if (value) {
$.cookie(name, 1, { expires: date });
} else {
$.cookie(name, null);
}
cookie = $.cookie(name);
alert(cookie);
})
These two pieces of code should be combined as such
$(document).ready( function() {
//first code above
//second code above
});

Categories