I have tried some tips I was given on regards URL encoding but I have no success so far. First, I was given this format,
var url = "http://www.polyvore.com/cgi/add?title="
+ encodeURIComponent(%%GLOBAL_ProductName%%)
+ "&url=" + encodeURIComponent("http://lilaboutique.co.uk/products/"
+ encodeURIComponent(%%GLOBAL_ProductName%%)
+ "&imgurl=" + encodeURIComponent(%%GLOBAL_ThumbImageURL%%)
+ "&desc=" + encodeURIComponent(%%GLOBAL_ProductDesc%%)
+ "&price=" + encodeURIComponent(%%GLOBAL_ProductPrice%%));
which never got to be passed to the href dunno for what reason. Then I played with it some more,
var url = "http://www.polyvore.com/cgi/add?title=encodeURIComponent(%%GLOBAL_ProductName%%)&url=http://lilaboutique.co.uk/products/encodeURIComponent(%%GLOBAL_ProductName%%)&imgurl=encodeURIComponent(%%GLOBAL_ThumbImageURL%%)&desc=encodeURIComponent(%%GLOBAL_ProductDesc%%)&price=encodeURIComponent(%%GLOBAL_ProductPrice%%)";
this time the URL was passed but the values were mixed between the appropriate and other fields displaying the encoding function itself.
Any help clarifying my mistakes is greatly appreciated. I would like to encode just price and description, seems to be the fields giving problems.
A regular link does render without problems
var url = "www.google.com";
var myAnchor = document.getElementById('myAnchor');
myAnchor.href = url;
Thanks for any help
Nicer, cleaner way of doing this:
var toEncode = {
title: '%%GLOBAL_ProductName%%',
url: 'http://lilaboutique.co.uk/products/%%GLOBAL_ProductName%%',
imgurl: '%%GLOBAL_ThumbImageURL%%',
desc: '%%GLOBAL_ProductDesc%%',
price: '%%GLOBAL_ProductPrice%%'
};
var index, queryString = '';
for (index in toEncode)
{
queryString += index + '=' + encodeURIComponent(toEncode[index]) + '&';
}
var url = "http://www.polyvore.com/cgi/add?" + queryString;
jQuery's $.param(obj) is very nice.
In general though I would take a similar approach if you wanted to roll your own. Make a function that accepts an Object, and returns a query string. Then in your server template, you have:
var urlData = {
url: "http://lilaboutique.co.uk/products/",
imgurl: "%%GLOBAL_ThumbImageURL%%",
desc: "%%GLOBAL_ProductDesc%%"
// etc...
}
var url = "http://www.polyvore.com/cgi/add?" + $.param(urlData);
Or whatever conversion function you want to use.
Related
I have been digging in some javascript api's lately and I found the following line:
get_url_info: function($db_link) {
var ldst_href;
if ($db_link.data('ldst-href')) {
ldst_href = $db_link.data('ldst-href');
}
else {
ldst_href = $db_link.attr('href');
}
var matchs = ldst_href.match(/^http:\/\/([^\.]+)\..*playguide\/db\/(.*?)\/?(#.+)?$/);
var subdomain = matchs[1];
var path = matchs[2];
if (!eorzeadb.dynamic_tooltip && eorzeadb.versions.data) {
url = eorzeadb.cdn_prefix + 'pc/tooltip/' + eorzeadb.versions.data +
'/' + subdomain + '/' + path + '.js';
}
else {
url = ldst_href + '/jsonp/';
}
return {
'url': url,
'data_key': subdomain + '/' + path
};
},
This result is supposed the return an array which I assume is contained in the link. I'm having a hard time decrypting the link tho.
Does anybody have any experience with these kinds of links or a way that I could start out?
http://regexr.com/
Here you can understand all the parts of the regex. Basically, is looking for a pattern like this:
http://(blablah).playguide/db/(OPTIONAL)(optional/)#(probably some id)
The result will be an array with the original link, followed by the domain, the first optional argument, and the hashtag, something like this
["http://(blablah).playguide/db/(OPTIONAL)(optional/)#(probably some id)", "(blablah)", "(OPTIONAL)(optional/)", "#(probably some id)"]
It will then use that information to build a different link
var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()
I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}
I know that the each() in jQuery is synchronous, but it doesn't seem to behaving that way. When I do this:
$('#findRankBtn').click(function () {
var websiteURL = $('#websiteURL').val();
var searchTerms = $('#searchTerm').val();
var pageNumber = $('#currentPage').val();
//INSERTS A + FOR EVERY SPACE
var searchTerms = searchTerms.replace(" ", "+");
searchGoogle(searchTerms, pageNumber, websiteURL);
});
function searchGoogle(searchTerms, pageNumber, websiteURL) {
$.getJSON("https://www.googleapis.com/customsearch/v1?key=AIzaSyDPuIrijE0IQ6330vMLN2p-L_4J6y_G60c&cx=013036536707430787589:_pqjad5hr1a&q=" + searchTerms + "&alt=json&start=" + pageNumber,
function (recievedData) {
//console.log(recievedData);
$.each(recievedData.items, function (i, item) {
$('#resultsDiv').append('<p class="resultLink">' + item.link + '</p>');
var linkAddress = $('.resultLink:last').text();
if (linkAddress.indexOf(websiteURL) !== -1) {
alert('found');
$('.resultLink:last').attr('class', 'yourLink');
$('#ifFound').attr('value', 'true');
}
});
var ifFound = $('#ifFound').val();
var currentPage = $('#currentPage').val();
var nextPage = CurrentPage + 1;
if (ifFound == 'false') {
//INCREMENT PAGE
$('#currentPage').attr('value', nextPage);
//GRAB DATA AGAIN
var websiteURL = $('#websiteURL').val();
var searchTerms = $('#searchTerm').val();
//INSERTS A + FOR EVERY SPACE
var searchTerms = searchTerms.replace(" ", "+");
//SEARCH GOOGLE
searchGoogle(searchTerms, nextPage);
}
});
}
Basically if it doesn't find the desired link on the first page of results, it should go on to the next page. I have a working fiddle for just the first page here: http://jsfiddle.net/p8DY3/1/
so how can I get searchGoogle() to run until it finds what it's looking for?
Maybe there's a better way of going about it that's in the Google API that I don't know about?
Sorry if my question is amateur, I've only begun to learn JavaScript on my own a month ago.
First you should make sure you are not hitting some sort of rate limit from Google. Look at your Network tab to see if the requests are coming back correctly.
First issue I see is bad math.
var currentPage = $('#currentPage').val(); is a string
Here var nextPage = CurrentPage + 1; you are treating it as a number.
You got to convert the string to a number before you add to it. You are doing string concatenation!.
var nextPage = parseInt(CurrentPage,10) + 1;
NITPICKS
Do not store things in inputs. Use variables, it will make things go so much faster. DOM lookup/manipulation is slow.
Why are you reinventing addClass and val()
$('.resultLink:last').attr('class', 'yourLink');
$('#currentPage').attr('value', nextPage);
should be
$('.resultLink:last').addClass('yourLink');
$('#currentPage').val(nextPage);
Why are you grabbing the search terms and website url again? You already have them passed into the function?
Finally your problem
searchGoogle(searchTerms, nextPage); <-- What are you missing here?
function searchGoogle(searchTerms, pageNumber, websiteURL) { <--what it is expecting
You are passing in 2 things when it wants 3.
I'm pretty new to jQuery and Greasemonkey, but I want to reform a URL.
For example, given:
http://www.example.com/index.php?value1=blabla1&sid=blabla2&mid=blabla3
I want:
link://www.example.com/blabla1/data/blabla2/blabla3.ext
I tried code like this:
var sid=document.URL.substring(document.URL.indexOf('sid=')+15);
// How do I set the length of blabla2 ? -7 ?
Hopefully someone understands what I mean and can help me out a little.
Use regular-expression searches to get the values.
If you know the param names in advance, it's more straightforward than it looks...
var searchableStr = document.URL + '&';
var value1 = searchableStr.match (/[\?\&]value1=([^\&\#]+)[\&\#]/i) [1];
var sid = searchableStr.match (/[\?\&]sid=([^\&\#]+)[\&\#]/i) [1];
var mid = searchableStr.match (/[\?\&]mid=([^\&\#]+)[\&\#]/i) [1];
.
The last bit is then something like:
var domain = searchableStr.match (/\/\/([w\.]*[^\/]+)/i) [1];
var newlink = '//' + domain + '/' + value1 + '/data/' + sid + '/' + mid + '.ext';
.
.
PS: It's only slightly more work if you don't know the names in advance.
PPS: This is educational code. Beware of extra spaces and malicious data, when using in the wild.