jQuery - saving/using cookies - php

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
});

Related

Live filter in Laravel

I have a form that looks like below.
I have three "white" dropdowns to filter the value for the Equipment Registration Tag dropdown ( The values of the dropdown input field that has the Equipment Registration Tag label will only come out after the user selects values for the three "white" dropdowns). So the Equipment Registration Tag values will differ based on the "white" dropdowns value.
I want it to be a live filter, the dropdown options will change immediately every time user selects the "white" dropdown value. Currently, my approach is to use the onchange=" this.form.submit()" attribute on the "white" dropdowns and return the values after the filter, but I realize this method has a disadvantage which is a user might accidentally submit the form when changing the value of "white" dropdowns. How can I prevent this and only allow users to submit the form by clicking the save button?
$this->Calibration_Location = $request->get('selected_location');
$this->Calibration_Category = $request->get('selected_category');
$this->categories = Equipment::select('Category')->distinct()->get()->toArray();
$this->locations = Equipment::select('Location')->distinct()->get()->toArray();
$matchThese = ['Category' => $this->Calibration_Category, 'Location' => $this->Calibration_Location];
$this->Registration_Select_Tags = Equipment::select('Registration Tag')->distinct()->where($matchThese)->get();
I have also tried jQuery, but I can only trigger by a specified dropdown field, not any one of them.
<script type="text/javascript">
$(document).ready(function() {
var location, category
$('#selected_transfer_location').change(function() {
location = $(this).val();
console.log(location);
$('#selected_transfer_category').change(function() {
category = $(this).val();
console.log(category);
});
// $('#transfer_registration_tag').find('option').not(':first').remove();
$.ajax({
url: 'Transaction/' + location + '/' + category,
type: 'get',
dataType: 'json',
success: function(response) {
var len = 0;
if (response.data != null) {
len = response.data.length;
}
if (len > 0) {
for (var i = 0; i < len; i++) {
var id = response.data[i]['Registration Tag'];
var name = response.data[i]['Registration Tag'];
var option = "<option value='" + id + "'>" + name +
"</option>";
$("#transfer_registration_tag").append(option);
}
}
}
})
});
});
</script>
I hope my question is clear, still new to Laravel and I hope could receive some hints from you.
First approach could be that, you use call ajax Query on change of each on of them and fetch filtered results. Something like this:
$('#dropdown1, #dropdown2, #dropdown3').change(function(){
var val1 = $('#dropdown1').val();
var val2 = $('#dropdown2').val();
var val3 = $('#dropdown3').val();
//And then your ajax call here to fetch filtered results.
});
Only issue is this Ajax call will occur min 3 times, one for each of them.
Second approach could be you give small button below those dropdowns, something like FetchTags. When user selects all the 3 values, will click on that button and you call your ajax onClick of that btn. So that your Ajax will be called only once.
You can use livewire to do that. It easy.
To install it, you have to use composer by taping the fowllowing command:
composer req livewire/livewire
Please check this tutorial to see how to how to do what you want to do using the framework.

Conflicting jquery functions

I have built two functions which work separately (when the other is deleted) but do not work together. The overall aim is that when a person selects the number of results they want to see per page, this then reloads the page, and the value is put in the url and then retrieved using get in php; and then on the new page the selected value in the drop down menu to is the value what triggered the reload.
Jquery
$(document).ready(function(){
//the first section takes the value from the php script and then selects the option if it's not null - this works fine on it's own
var data = "<?php echo $rp;?>";
if (data){
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
//this too works fine on it's own but not with the above
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
Together, the first works fine, in that it re-selects the right value if, say, I put ?results=50 after sales.php but then the jQuery to trigger the reload doesn't work. What am I doing wrong?
Just to clarify. The first page is called "sales.php" and the drop down menu has the currently selected value of "10", with 25 and 50 being other options. When I click on another number the jquery doesn't work. However should I type into the url the ending "?result=50", for example, it does work; and the drop down menu now shows 50; when i click on ten, the url updates, and the drop down shows ten also; the problem then is they seem to conflict only at the start, as it were.
It would seem the problem may concern how jquery deals with php. Take for example the following first example which works, and then the second which doesn't:
1)
$(document).ready(function(){
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
2) This change function however will not trigger a reload of the page because of the inclusion of the php defined jquery variable.
$(document).ready(function(){
var data = "<?php echo $rp;?>";
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
This achieves what I want (I don't know if the php posed a problem or not). The function is from here - Get url parameter jquery Or How to Get Query String Values In js.
Also, I'm surprised nobody more experienced than me didn't point out what also seems to have made a difference; the "first" function in the original post needs to in fact be second.
So the below will reload a new page, when a user clicks on an option in a select menu with pre-defined options for how many results they want to see per page; this value will then show in the url, and, importantly, the current select value of the select menu will now be this value also; this is important so that if the user goes back to the original number of views, the change() function works still.
$(document).ready(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var data = getUrlParameter('results');
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
if (data)
{
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
});

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 :)

Submit jQuery multiple date picker form as POST data

I love this jQuery datepicker that I want to implement on a PHP form with other input boxes
http://multidatespickr.sourceforge.net/
When the user hits a submit button they are brought to another page update.php where the form data is obtained via POST.
I'm looking for a line to add to the javascript so I can somehow access the array of multiple dates in the multiple datepicker via POST:
var latestMDPver = $.ui.multiDatesPicker.version;
var lastMDPupdate = '2012-03-28';
var dates = $('#simpliest-usage').multiDatesPicker('getDates');
// Version //
//$('title').append(' v' + latestMDPver);
$('.mdp-version').text('v' + latestMDPver);
$('#mdp-title').attr('title', 'last update: ' + lastMDPupdate);
// Documentation //
$('i:contains(type)').attr('title', '[Optional] accepted values are: "allowed" [default]; "disabled".');
$('i:contains(format)').attr('title', '[Optional] accepted values are: "string" [default]; "object".');
$('#how-to h4').each(function () {
var a = $(this).closest('li').attr('id');
$(this).wrap('<'+'a href="#'+a+'"></'+'a>');
});
$('#demos .demo').each(function () {
var id = $(this).find('.box').attr('id') + '-demo';
$(this).attr('id', id)
.find('h3').wrapInner('<'+'a href="#'+id+'"></'+'a>');
});
// Run Demos
$('.demo .code').each(function() {
eval($(this).attr('title','NEW: edit this code and test it!').text());
this.contentEditable = true;
}).focus(function() {
if(!$(this).next().hasClass('test'))
$(this)
.after('<button class="test">test</button>')
.next('.test').click(function() {
$(this).closest('.demo').find('.box').removeClass('hasDatepicker').empty();
eval($(this).prev().text());
$(this).remove();
});
});
});
Looking at the plugin you can store the range as a common seperated list in a regular input field. Use jquery to disable to field from direct entry so people can't "mess it up" then after you post you an implode the field on a comma and then you will have your array.
http://multidatespickr.sourceforge.net/#undefined-demo
I'm not sure if that's what you're looking for, but if you need to access the dates passed to the script via POST just do this:
$dates = explode(',', $_POST['simpliest-usage']);

Store Form Values In Cookie

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);

Categories