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 :)
Related
So I need to detect webp support using modernizer, and then do some processign in PHP depending on the outcome of the result.
Now at first I thought I could set a cookie and get the cookie using PHP like so:
JS:
Modernizr.on('webp', function (result) {
if (result) {
setCookie("webpissupported", "yes", "365");
}
});
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
PHP:
$userAvatar = um_get_avatar_uri( um_profile('profile_photo'), 190 );
$patterns = array("/.jpg/", "/.jpeg/", "/.png/");
if (isset($_COOKIE['webpsupport']))
$userAvatar = preg_replace($patterns, "_result.webp", $userAvatar);
Now the problem with the above code is that I'm using the wordpress plugin w3 total cache, with the page cache enabled. this is causing the cookie to be cached and producing unexpected results.
So then I thought maybe I could do something like this:
<script type="text/javascript">
Modernizr.on("webp", function (result) {
if (result) {
<?php $webpSupport = true; ?>
}
});
</script>
But this will not work.
Anyone know how I might get around this problem.
You have mixed (client) browser-side processing with server-side (PHP). In your example, PHP block of code shall be executed regardless of what is to be processed later by browser/JS (or won't at all, in case of no JS browser). So, $webpSupport variable in this case and example shall be what you assign to it in order from top to bottom.
One way to achieve what you are after is to have JS cookie set, setCookie("webpissupported", "yes", "365"); and in the next page view read the $_COOKIE['webpissupported'] and serve images according to it.
Remember, webp is not a standard, although present in 72.85% browsers according to caniuse.com /StatCounter. You have to use it as progressive enhancement.
I am currently trying to retrieve some data from book search sites and populate a personal database with that data. My idea is to inject the necessary jQuery on the page, so that when I see a title I think I'd like to return to in future, I can then just click a cheeckbox, make necessary additional comments, which I then hope to submit by AJAX to a PHP script which then populates my MySQL database for me with the appropriate title.
Do look at this example for a library catalogue:
// for every book entry, append checkboxes
$('.document-frame').append('<p>Choose:?<input type="checkbox" class="Jcustom_c" /></p><p>Serendepity?:<input type="checkbox" class="Jserep" /></p><p>Include snippet?:<input type="checkbox" class="Jsnippet" /></p>');
// append a Submit button at the bottom of the page, and a blank div for feedback upon success in POST-ing the necessary data
$('#resultPage').append('<input id="Justin" class="Jcustom" type="submit"/><div id="Jfeedback"></div>');
// whenever my checkbox is checked, retrieve / "scrape" the necessary book data
$('.Jcustom_c').change(function() {
if ($(this).is(':checked'))
{
var title = $(this).parent().parent().find('.title a').text();
var author = $(this).parent().parent().find('.authors a').text();
var publishd = $(this).parent().parent().find('.publisher').text();
var status = $(this).parent().parent().find('.metadata .summary').text();
var img_link = $(this).parent().parent().find('img.artwork').attr("src")
// create an XML string from that data. Escape "<" and ">", otherwise when we append the string to the browser for feedback, the browser will not render them correctly.
var appended = '<div class="Jappended"><item><title>' + title + '</title><author>' + author + '</author><publisher_n_edn>' + publishd + '</publisher_n_edn><status>' + status + '</status><image>' + img_link + '</image><serep>N</serep></item></div>';
// show the string just below the book title. Hence if I "pick" the book from the catalogue, the XML string will show up to confirm my the fact that I "picked" it.
$(this).parent().parent().append(appended);
}
// if I uncheck the box, I remove the XML string
else {
$(this).parent().nextAll(".Jappended").remove(appended);
$(this).parent().prevAll(".Jappended").remove(appended);
}
});
And then I have the AJAX:
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
$(".Jappended").each(function() {
var placeh = $(this).text();
string = string + placeh;
$('.results_container').append(string);
})
// these come from <textarea> boxes I append to the end of the page just before the Submit button. (Above, I did not include the jQuery to append these boxes.)
var odp = $("#odp").val()
var mre = $("#motivation_revisit").val()
var mra = $("#motivation_rationale").val()
var stu = $(".hdr_block h5 span").text()
var string = string + "<odpath>" + odp + "</odpath><stused>" + stu + "</stused><motivation><revisit>" + mre + "</revisit><rationale>" + mra + "</rationale></motivation></itemset>"
var post_var = { xml_string : string, source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
$('#Jfeedback').html(data);
});
My problem is that I can't seem to get the AJAX to work: When I click on my Submit button, I do not see the output I would expect when I used the exact same jQuery on an HTML file I called from localhost. This, which I called using http://localhost:8888/some_html.html worked:
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready( function() {
...
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
/*
$(".Jappended").each(function() {
var post_var = { xml_string : "hello", source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
// if (data == "Success") {
$('#Jfeedback').html(data);
// }
});
});
});
</script>
<body>
...
</body>
</html>
db-ajax.php is simply:
echo "Success";
I have read this post: jQuery cannot retrieve data from localhost, which mentions something about "JavaScript cannot currently make direct requests cross-domain due to the Same-origin Policy". Is this the reason why my code didn't work on the external page? If yes, what can I do to make the code work, or what other approaches can I adopt to achieve the same goal? I have mutliple book search sites that I am working on, and many of these do not have an API where I can extract data directly from.
Thank you in advance.
P.S.: I've also tried the suggestion by CG_DEV on How to use type: "POST" in jsonp ajax call, which says that $.post can be done with jsonp, which is the data type to use for cross-domain AJAX. Result: On Firebug I do see the POST request being made. But my function callback is not fired, and firebug doesn't register a Response body when at least "Success" should be returned.
you can set allow cross origin resource sharing
Follow two steps:
From server set this on response header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:*
//* if you want to allow it for all origin domain , or you can specify origin domains also to which you want to allow cors.
In client side add this on your page
$.support.cors = true;
Cons: It is not fully supported on ie < ie10.
I have a form that does a lookup on a database the lookup is done using load(). This is fine.
What I've like to do is to read the value of an input which is returned via the php.
I was thinking that I needed to use the .live() method but I'm not certain how.
My current code is:
var recordCount = $("input[name=noOfCusts]").val();
console.log("Number is " + recordCount)
So input[name=noOfCusts] is loaded from PHP so I can't get at it. I just get a value of undefined.
How do I roll live() into var recordCount = $("input[name=noOfCusts]").val();
Thanks
My load code is
$("input[name=findCust]").keyup(function(){
var key = $(this).val();
var type = 1;
$("div#CustomerResults").html("<img src='../images/loading.gif' alt='loading'/>").delay('500').load("../../ajax/customerFinder.php",{"key":key,"type":type}).fadeIn(300);
//#############################################
// Extra bit to make the search form work with a return
$("input[name=findCust]").live('keyup',function(){
var recordCount = $("input[name=noOfCusts]").val();
console.log("Number is " + recordCount)
});
//var recordCount = $("input[name=noOfCusts]").find("input[name=noOfCusts]").val();
//
//$('input[name="noOfCusts"]').val(data);
//console.log("Number is " + data)
//#############################################
});
Instead of returning an HTML input tag, return just the value for that input that is already present within HTML DOM.
Then in load call on success set the obtained value to that input:
// success
$('input[name="noOfCusts"]').val(data);
alert(data);
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);
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
});