I've got these two functions:-
function BlogsButtons() {
$.removeCookie('BlogURLs', { expires: 7, path: '/en/blogs/' });
var urls = "";
$("#list-of-blogs div.news-article").each(function() {
urls += $(this).find('a:first-child').attr('href');
if(!$(this).is(":last-child")) {
urls += ",";
}
});
$.cookie('BlogURLs', urls, { expires: 7, path: '/en/blogs/' });
var a = 1;
}
and
function BlogsNextLastButtons() {
var blogsURLs = $.cookie('BlogURLs', { expires: 7, path: '/en/blogs/' });
// .. to do rest of function here
}
I have a page which lists blogs, and I want to get the list of URL's and comma separate them and store them in a cookie. Then on the page that has the actual article on, I want to retrieve this list from the cookie, split it by comma and use basic array surfing to find the item in the list before the current page URL and then item after. The logic for this works.
In the second function on that first line, when I try to get back the value of $.cookie('BlogURLs'), the console shows me [object Object]. I've read on another post that this can be caused by a cookie being overwritten, but this is definitely the only place on the site where a cookie with such a name is used.
Also, interesting to note is that the line of code var a = 1, I can see the cookie value here in the correct format. So whatever causes this happens after the page with the actual article on loads up.
Stuff I've tried:-
Renaming the cookie name to something absurd that can't possibly be used.
Changing the path of the cookie
Instead of doing removeCookie, I tried setting the cookie to null, empty string and an expiry time of -1.
Nothing seems to work. In an exact duplicate of this function above, we have no issues, the cookie name there is different again, as is the path.
Can anyone help?
Thanks.
Related
I'm trying to do a form of URL cycling but instead of given URLS, I want to append values from a JSON object to the url and cycle those.
I have the main idea working but it's not quite right. Right now the link to the page in question carries a value for 'display' so an example would be
showdisplay.php?display=3
This runs a query to get all page info for any pages assigned to display 3, and this works.
What I want, once that query returns my result which is then JSON encoded, is to loop throught the JSON object, append the pageID of the first element in the URL, and after the duration of the element (in seconds) refresh the page and do the same thing again. Continue looping this and going back to the first element at the end of the object.
SO given this JSON object:
[{"pageID":"104",
"display_id":"3",
"duration":"56",
"page_id":"104",
},
{"pageID":"116",
"display_id":"3",
"duration":"54",
"page_id":"116",
}]
Here's what I expect when clicking the link ```Link to Page:
On immediate pageload, the URL would be showdisplay.php?display=3&pageID=104
After 56 seconds ('duration' in JSON), refresh page and set URL to showdisplay.php?display=3&pageID=116
After 54 seconds, refresh again back to pageID 104
Basically, when following that link, the url should never just say showdisplay.php?display=3 but should always have a pageID assinged to it from the JSON
My script:
<script type="text/javascript">
let obj = <?php echo $showDisplays; ?>;
let params = new URL(document.location).searchParams;
params.set("pageID", obj[0].pageID);
params.set("display", obj[0].display_id);
let url = window.location.href.split('?')[0];
let nextURL = url + "?" + params.toString();
window.setTimeout(function () {
window.location.href = nextURL;
}, obj.duration * 1000);
obj.forEach(function(o){console.log(o)})
</script>
I've been stuck on this for days and have no idea what I'm doing wrong or how to loop this properly. I feel like it shouldn't be too dificult but I'm not a JS coder by nature and I'm totally stuck. Can anyone help me rectify this and loop properly?
I'd like to perform a redirect, but I also wish to send additional information along with it.
I've tried to change the value of window.location.href but that doesn't seem to pass along the extra information.
I also get how I can do
$.get(
new_url,
{data : "mydata"},
function(data) {
alert('page content: ' + data);
}
);
and that will display the html content of the new page, but that doesn't help with actually getting there.
How can I achieve this?
Edit: I feel as if I must be phrasing this terribly because I'm pretty sure this is an easy/common task. This shouldn't be something that would require cookies - it should basically be like a post request (I think).
You have a few different options for this:
URI Variables - You can append extra data to the URL by appending a question mark (?) followed by a set of key-value separated by an ampersand (=) with each variable being separated by an ampersand (&). For instance, http://www.google.com/search?q=javascript+url+variables&ie=UTF-8 gives you a link to a Google search for "javascript url variables" using UTF-8 encoding. Your PHP code or JavaScript would need to handle passing along and processing these variables. If using JavaScript a nice library for processing URLs is URI.js or using PHP you can use the parse_url and http_build_query functions. You can use this with window.location.href; for instance: window.location.href = "http://www.google.com/search?q=javascript+url+variables&ie=UTF-8" (replace the Google URL with the one you created or set in a variable).
Storage API - You can use the localStorage or sessionStorage properties to store and retrieve information using JavaScript (information is stored in the user's browser - supported by IE 8 and newer and all other major browsers). Note that this is JavaScript only unless you grab the data with JavaScript and pass it to your PHP server through URL variables, form, AJAX request, etc.
Cookie - You can store additional information inside a cookie - however this is more difficult since you have to setup your variables as a parsable string (possibly JSON) and remember to encode/decode the string when setting/getting the cookie. I don't recommend this method.
IndexedDB API - This is a more advanced client-side/browser storage mechanism and currently only supported in IE 10 and newer (and nearly all other browsers). There are also still changes being made to the standard which means newer versions of browsers could break current implementations or be buggy. If all you need is simple key-value storage (not an SQL-like database) then you should stick with one of the above options.
You can use the window open method to redirect your user,and remember to use "_self"
window.open('url','_self');
Preferably you'd store the data in localStorage and fall back to a cookie (I really like js-cookie).
Here are the two helper functions you need to store and retrieve data:
function setMultiPageData(itemName, data) {
var dataStr = JSON.stringify(data);
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
localStorage.setItem(itemName, dataStr);
}
else {
Cookies.set(itemName, dataStr, { path: '/' }); // path set to root to make cookie available on any page
}
}
function getMultiPageData(itemName) {
var data = null;
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
data = localStorage.getItem(itemName);
}
if (!hasLocalStorage || data === null) {
data = Cookies.get(itemName);
}
var parsedObject = null;
try {
parsedObject = JSON.parse(data);
}
catch (ex) {
console.log(ex); // remove in production
}
return parsedObject;
}
usage:
var data = { first: 'this is the first thing', second: 'this is the second thing' };
setMultiPageData('stackoverflow-test', data);
// go to a new page
var retrievedData = getMultiPageData('stackoverflow-test');
if (retrievedData === null) {
console.log('something went wrong')
}
else {
console.log(retrievedData); // { first: 'this is the first thing', second: 'this is the second thing' }
}
I'm working on a school project where I'm trying to make a search function for The New York Times Article Search API.
I have a problem with one of their search filters as when I run the function I get error 400 as for some reason it can't read the url encoding. The fun thing is if I replace all the %3D's with = and the %26's with & in my own URL it works and I can see the API responds correctly.
if($('#date1').is(':checked')) {date="day_of_week&begin_date=18500101&end_date=19000101";}
if($('#date2').is(':checked')) {date="day_of_week&begin_date=19000101&end_date=19500101";}
if($('#date3').is(':checked')) {date="day_of_week&begin_date=19500101&end_date=20000101";}
if($('#date4').is(':checked')) {date="day_of_week&begin_date=20000101&end_date=20150101";}
$.getJSON('http://api.nytimes.com/svc/search/v2/articlesearch.json',
{'api-key': 'XXXXXXXXXXXXXXXXXXXXXXX',
'fq': 'headline:("'+sogestreng.toLowerCase()+'")'+" AND "+finalSections,
'facet_field': date},
This code returns "http://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=XXXXXXXXXXXXXXXXXXXXXXX&fq=headline%3A(%22dubai%22)+AND+section_name.contains%3A(%22Sports%2C+%22)&facet_field=day_of_week%26begin_date%3D20000101%26end_date%3D20150101"
While if I manually replace the last part of the url encoding and open it in my browser I get the result I'm looking for.
I do this by changing:
"&facet_field=day_of_week%26begin_date%3D20000101%26end_date%3D20150101"
to
"&facet_field=day_of_week&begin_date=20000101&end_date=20150101"
Also to clarify, the "fq" criteria works perfectly fine, it's just the facet_field.
How can this be? And is there any fix for it?
You're shoving the description of several fields into one field's value. To get the results you want, try:
var begin_date, end_date;
if($('#date1').is(':checked')) {
begin_date = 18500101;
end_date = 19000101;
}
else if($('#date2').is(':checked')) {
// etc.
}
$.getJSON('http://api.nytimes.com/svc/search/v2/articlesearch.json',
{
'api-key': 'XXXXXXXXXXXXXXXXXXXXXXX',
'fq': 'headline:("'+sogestreng.toLowerCase()+'")'+" AND "+finalSections,
'facet_field': 'day_of_week',
'begin_date': begin_date,
'end_date': end_date
},
// ...
I am working on a feature for my site that allows the user to use the back button and not have to load more database results.
I start by loading 16 results, and then there is a load more button which loads the next 16. In the ajax success i change the href of this button so the url changes to e.g. domain.com/#1 to #2.
I wrote this last night:
// First get the page URL and split it via # signs
var parts = location.href.split('#');
// now we run a check on the URL and see how many 'parts' there are
if(parts.length > 1)
{
var params = parts[0].split('?');
var mark = '?';
if(params.length > 1)
{
mark = '&';
}
location.href = parts[0] + mark + 'page=' + parts[1];
}
Which gets the URL, and redirects the user the same page but converts the fragment number to a page number. From this i then use a PHP $_GET and set the limit claus last value from that.
This works fine. But its primitive. Let for instance say i push back and the URL becomes:
www.domain.com/?page=1
If i then click to load some more data, the page url becomes:
www.domain.com/?page=1#2
If the user then visits another page and comes back then they get directed to:
www.domain.com/?page=1&page=1
Whats the best way around this? I was thinking of running a check on the URL at the same time as looking for a fragment and if the URL has a page variable i then add that variable to the fragment variable and the page URL becomes ?page=THE SUM NUMBER
Any help on modifying the snippet i posted above to check the URL for a page value and then add the two together before the redirection?
Thanks!
You need to use location.search to get the query string on a URL:
var queryParameters = location.search.split('&');
Then you can loop through the queryParameters and check if page is set:
var pageNumber = 0;
for(var i = 0; i < queryParameters.length; i++)
{
var keyvaluePair = queryParameters[i].split('=');
if(keyvaluePair[0] == 'page')
{
pageNumber = keyvaluePair[1];
break;
}
}
Please see the documentation on the MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
You might also find this example useful for returning one value:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location#Example_.236.3A_Get_the_value_of_a_single_window.location.search_key.3A
If you want to get the information after the #, you need to use location.hash. The MDN documentation I linked also has information on location.hash.
I have called one PHP page inside an iframe
I have stored some values in cookies. I want to read those cookies values from that page to other page.
I used jQuery to read the cookie.
var value = $.cookie('artname');
'artname' is the cookie name.
But it is displaying null because the cookie path is different. The path is /v/abcfile/frontend/.
But the path for the other cookies on the page i am trying to get is /.
I tried with this:
top.jQuery.cookie('artname');
But it's still showing me the same.
For path ii have tried with:
var value = $.cookie("artname", { path:'/v/vspfiles/frontend/' });
Its still showing me the null value.
How can I get value of cookie?
When you save your cookies, set path to "/". Cookie will be available on all pages
$.cookie('artname', 'value', { path:'/'});
This worked for me:
$.cookie.defaults = { path: '/' };
$.cookie("foo", "value" );