JavaScript redirect in functions - javascript

I have a php page that displays a list of items, when one is clicked it returns me to the main menu a series of extras get values. These I grab using JavaScript and activate a function. This affects the localStorage very quickly and then I want to switch the url again but for some reason window.location isn't forwarding me at all. If it makes any difference, I am redirecting to the same url just taking away one of the two get values.
Here is the source:
//When the item is initially clicked, I have used alert to make sure there is a valid 'id'
function remo(id) {
window.location = "http://www.example.co.uk/?s=&r=" + id;
}
//When the JS reads the URL for the get values
var rcheck = url.search("r=");
if(rcheck>=0) {var re = getUrlVars()["r"];remove(re);}
//The function getUrlVars()
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
//The remove() function called 2 statements ago as remove(re);
function remove(id) {
localStorage['KFAch' + id] = 0;
var url = "http://games.thanetdragons.co.uk/killingfloor/?s=";
window.location = url;
window.location.replace(url);
window.location.href = url;
$(location).attr('href', url);
}
As you can see I am trying extensive redirect options.
Everything works fine, it even switched the localStorage value correctly, except, it doesn't forward my webpage to the next URL that no longer has the r parameter.
Is there any reason for this?

Related

Javascript fetch getting undefined URL on window.popstate

I'm trying to fetch content from a php page. I have a fetch call + a history.pushState firing on click, which are both working fine, but window.popstate is returning an error when going back by pressing the browser's back button. The error is, that window.popstate doesn't know what url to fetch when going back.
Unfortunately I can't figure out how to pass the right url variable to window.popstate.
// the code stripped fetch function
var load = function(url){
fetch(url, {
method: "GET"
}).then(function(response) {
response.text().then(function(text) {
// parsing and temporary placing fetched content into a fragment
var content = new DOMParser().parseFromString(text, "text/html"),
bodyPart = content.querySelector('main'),
fragmentElement = document.createDocumentFragment(),
tempElement = fragmentElement.appendChild(bodyPart);
// replacing the current content with the fragment
document.body.replaceChild(tempElement, document.querySelector('main'));
// need to assign the fetch on click function again, otherwise it won't work on the dynamically added (the fetched) links
clickOnPJAXLink();
});
});
}
// the click function if clicking on any link function to start fetching content
var clickOnPJAXLink = function(url) {
document.querySelectorAll('A').forEach(a => {
a.addEventListener('click', (e) => {
e.preventDefault();
var url = e.currentTarget.getAttribute("href");
load(url);
history.pushState(url, "sometitle", url);
});
});
}
// load the function initially on the home page
clickOnPJAXLink();
// popstate for back button
window.addEventListener('popstate', function (e) {
var state = e.state;
if (state !== null) {
load(url);
console.log(url)
}
});
The window.popstate returns the error, that var url is undefined and thus of course cannot fetch the before (the history back) content.
Many thanks for any tips!
history.pushState takes a data object as the first parameter, not a string- try history.pushState({url:e.currentTarget.getAttribute("href")} then e.state.url will equal the url you want to load.

How can I extract and then change the url path using javascript?

I am trying to extract part of the url and replace it with custom text using javascript.
For example, I want to fetch the current url such as:
mydomain.com/url_part_to_change/some-other-stuff
and then change that url to insert so that new new url is:
mydomain.com/new_url_part/some-other-stuff
Here is what I have:
function changeURL() {
var theURL = window.location.pathname;
theURL.replace("/url_part_to_change/", "/new_url_part/");
//Set URL
}
However, when I try to call the function changeURL(), it returns undefined instead of the new url.
For example if I do this:
alert(changeURL());
then what alerts is undefined
TL;DR
// update the pathname that will reload the page
window.location.pathname = myNewPathname;
Further Explanation:
Window.location ( image attached below ) provides you an object containing all the uri parts information. So, you can get this object via window.location and access the property pathname then do your stuffs. For example:
var locationObject = window.location;
var pathnameToChange = locationObject.pathname;
// do stuffs to "copy" of pathname, this will not reload the page
var myNewPathname = doSomethingMyPathname( pathnameToChange );
Additional Examples:
Alternatively, set new url using location.href. Check the MDN documentation for examples on location.assign(), location.replace(), location.reload() and notes on the different available functions
// ie.myNewUrl is something I created -> www.blah.com/updated/path
window.location.href = myNewUrl;
// or
window.location.assign(myNewUrl)
A window.location Object in Console
There are three references to further understand URI components
URI_scheme
Standards written by Tim Berners-Lee
MDN Location
Hope this helps.
This should work for you correctly:
function changeURL() {
// Get the url, just as you did
var theURL = window.location.pathname;
// Return the url
return theURL.replace("/url_part_to_change/", "/new_url_part/");
}
you are not returning any thing in function, Please make function like
function changeURL() {
var theURL = window.location.pathname;
return theURL.replace("/url_part_to_change/", "/new_url_part/");
//Set URL
}
As the others said, you don't return anything. What they are forgetting is that String.replace() just makes a copy of theURL and doesn't change theURL.
Try this:
function changeURL() {
var theURL = window.location.pathname;
theURL = theURL.replace("/url_part_to_change/", "new_url_part/");
//Set URL
return theURL;
}
alert(changeURL());
function changeURL() {
//set new path
window.location.pathname = "/new_url_part/";
//get new url
const newURL = window.location.href;
return newURL;
}
You forgot to return
function changeURL() {
var theURL = window.location.pathname;
var newURL = theURL.replace("/url_part_to_change/", "/new_url_part/");
//Set URL
return newURL;
}
alert(changeURL())//Now you won't see undefined.
This is quite an old post but just to add:
modifying window.location causes page navigations so if thats not desired create a new URL object and then you can modify the parts as needed.
in my case i needed to change the path to a value from a value in the querystring.
eg.
/*
* http://something.com/some/path?redirect=/some/other/path
* ->
* http://something.com/some/other/path
*/
let u = new URL(window.location.href)
u.pathname=u.searchParams.get("redirect")
u.searchParams.delete("redirect")
console.log(u.href)

Retrieving a specific link from url using javascript

I need to make a function in JavaScript to locate href inside the url that is given, and to return it as a string.
For example: http://stackoverflow.com/
So the function starts with: function example(url) {}
I want to find the first link inside this url that contain the words google.
In this page there is somewhere link like <a href:"http://google.com/asdasdadsa/asdada">
The function is to return the whole link as string.
So basically from what I can gather, you want to look at each link on the page and get the whole URL if it includes some string (i.e. google).
Here's a function that finds the first link matching a certain string:
function checkLinks( searchString ) {
var url;
// Go through each link
$('a').each( function ( ) {
// Check if the search string exists
if( $(this).attr('href').indexOf(searchString) != -1 ) {
url = $(this).attr('href');
// If we've found one, stop the each.
return false;
}
});
return url;
}
I've put together a jsfiddle showing an example of how this function could be used:
http://jsfiddle.net/K9KvS/1/
EDIT:
I've just seen you need to do this on a remote URL. You probably need to use AJAX to load in the code, then run this on the code you have. Unfortunately due to the same origin policy, you can't get this directly, so you'll need to run a server-side script on your server (e.g. using PHP) to load the content of the external page, then an AJAX call from your JS to pull it into your javascript.
Modified version to include an AJAX load of some code, then a find on that code:
// Create a function to do the actual search
function checkLinks( code, searchString ) {
var url;
// Search the code for all <a> tags, the loop over them
$(code).find('a').each( function ( ) {
// Check if there is a match (indexOf returns -1 if not)
if( $(this).attr('href').indexOf(searchString) != -1 ) {
// set the "url" variable to the href
url = $(this).attr('href');
// Stop looping
return false;
}
});
return url;
}
// Now, when the page loads, attach an AJAX call to a button with ID "linkchecker"
$( function ( ) {
$('#linkchecker').click( function( ) {
var code;
// Perform the AJAX call, load the data and call our function above to find "google.com"
$.get( 'load_code.php?url=http://www.google.com', function( data ) {
code = data;
alert( checkLinks( code, 'google.com' ) );
});
});
});
load_code.php would probably look something like this (probably with some error checking, etc):
<?php
$htm = file_get_contents($_GET['url']);
echo $htm;
?>
Update: Using Raw Javascript
We'll modify checkLinks from above to use raw Javascript:
function checkLinks( code, searchString )
{
var url;
// We need to create an HTML document element so we can use javascript dom functions on it.
var doc = document.createElement("html");
doc.innerHTML = code; // put the code into the document
// Get all links in the code
var links = doc.getElementsByTagName("a")
// Loop over all links
for (var i=0; i<links.length; i++) {
// Check if the search string (e.g "google.com") is found in the href of the link
if( links[i].getAttribute("href").indexOf(searchString) != -1 ) {
// Set it to the return value
url = links[i].getAttribute("href");
// stop looping
break;
}
}
return url;
}
So firstly, you need to set up the Ajax request object. The problem is this differs between browsers, so you need an unpleasant bit of code to generate it across them. The following is modified from the tiztag ajax tutorial:
function makeAJAXObject(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
return ajaxRequest;
}
Ok, so now we've got our AJAX object, we want to get it to load a page, and tell it how to handle what we get back:
/*
* A function to load a given URL and process the code from it.
* It takes three arguments:
* php_handler The name of the PHP file that will load the code (or ASP, or whatever you choose to use)
* url The URL to be loaded.
* searchString The string to find in the links (e.g. "google.com").
*/
function load_page( php_handler, url, searchString )
{
// Get the ajax object using our function above.
window.ajax = makeAJAXObject( );
// Tell the AJAX object what to do when it's loaded the page
window.ajax.onreadystatechange = function(){
if(window.ajax.readyState == 4){ // 4 means it's loaded ok.
// For simplicity, I'll just alert this, but you would put your code to handle what to do when a match is found here.
alert(checkLinks( window.ajax.responseText, searchString ));
}
}
// Set up the variables you want to sent to your PHP page (namely, the URL of the page to load)
var queryString = "?url=" + url;
// Load the PHP script that opens the page
window.ajax.open("GET", php_handler + queryString, true);
window.ajax.send(null);
}
The final thing is to attach this to a button when the page has loaded:
window.onload = function( ) {
document.getElementById('linkchecker').onclick = function( ) {
load_page('load_page.php', 'http://www.example.com', 'google');
}
}
Please note, there's likely to be built in WinJS functions to handle some of the AJAX stuff, but I've never tried Win 8 app development, so I don't know them!

Google Analytics - Using GET instead of POST

Ran into an issue where I need to use GET vs POST on a form method, but GATC cookie data is not being appended to the URL correctly, because the form's data is trumping Google's GATC data (using linkByPost).
I've read up on a potential solution posted here, but seems like an insane amount of work to make GET behave. I also stumbled upon another solution here, but IE doesn't respect anything after the 'anchor' portion of the url.
Anyone have any other ideas? If I can't handle this via JS, I will have to go into the script handling the form action and massage the querystring manually (assuming that GATC data is in $_REQUEST array). FTR, GATC data is not available via the $_REQUEST array, when using get.
For future reference, in case anyone runs into the same issue, this is the solution I implemented. I lifted some code from the answer to this SO post, and combined it with the idea behind this post, where it localizes the GATC data, and adds hidden fields to the form for each one.
Resulting code:
$(document).ready(function() {
$('#formId').submit(function(e) {
try {
e.preventDefault();
var form = this;
if (typeof _gat !== 'undefined') {
_gaq.push(['_linkByPost', this]);
var pageTracker = _gat._getTrackerByName();
var url = pageTracker._getLinkerUrl(form.action);
var match = url.match(/[^=&?]+\s*=\s*[^&#]*/g);
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
$('<input>').attr({
type: 'hidden',
name: name,
value: value
}).appendTo(form);
}
}
setTimeout(function() { form.submit(); }, 400);
} catch (e) { form.submit(); }
});
});
You can use jQuery serialize to get the form's elements, then _getLinkerUrl to append the cross-domain tracking data
$('#formID').submit(function(e) {
var pageTracker = _gat._getTrackerByName();
var url = this.action + '?' + $(this).serialize();
url = pageTracker._getLinkerUrl(url);
if (this.target != '_blank') location.href = url;
else window.open(url);
});

jQuery getJSON never enters its callback function

I've been sitting with this for hours now, and I cant understand why.
q is working. The URL does give me a proper JSON-response. It shows up as objects and arrays and whatnot under the JSON tab under the Net-tab in Firebug and all is fine. I've also tried with other URLs that i know work. Same thing happens.
I have another function elsewhere in my tiny app, wihch works fine, and is pretty much exactly the same thing, just another API and is called from elsewhere. Works fine, and the data variable is filled when it enters the getJSON-function. Here, data never gets filled with anything.
I've had breakpoints on every single line in Firebug, with no result. Nothing happens. It simply reaches the getJSON-line, and then skips to the debugger-statement after the function.
var usedTagCount = 10;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
for(var i = 0; i < usedTagCount; i++) {
tagString += query[i].key + ",";
}
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
debugger; /* It never gets here! */
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
debugger;
return flickrImageData;
}
Example of request URL (q):
http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=20&jsoncallback=?&tags=london,senior,iphone,royal,year,security,project,records,online,after,
I do wonder, since JSONView (the firefox plugin) cannot format it properly, that it isn't really JSON that is returned - the mime-type is text/html. Firebug, however, interprets it as JSON (as i stated above). And all the tag words come from another part of the app.
I think you might need to remove the
nojsoncallback=1
from your searchAPI string.
Flickr uses JSONP to enable cross domain calls. This method requires the JSON to be wrapped in a json callback, the nojsoncallback=1 parameter removes this wrapping.
EDIT: Apparently it works with nojsoncallback=1, I got this piece of code to work for me. What jQuery version are you using? JSONP is only available from 1.2 and up.
This works for me (slight modifications):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
var usedTagCount = 1;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
tagString = query;
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
}
search("cat");
</script>
When I try the url: http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=10&tags=mongo
it returns data, as it should -
try to change the getJSON to an $.ajax() and define a function jsonFlickrApi (data)
with the code you have in you callback function.
If that don't work - please post code to at jsbin.com <- so we can try it live - so much easier to debug.

Categories