I have an html page that people access using an affiliate link, so it has affiliate code in the url (http://www.site.com?cmpid=1234&aid=123). I want to add the cmpid and the aid to the form action url (so when submitted, it submits to the url /form.aspx but adds the cmpid and aid to the end, ie: form.aspx?cmpid=1234&aid=123).
I have no other option than javascript. I can't make this page php or aspx.
window.onload = function() {
var frm = document.forms[0];
frm.action = frm.action + location.search;
}
You can get access to the query string by location.search. Then you should be able to append it onto the form's action directly, something like the following:
// Get a reference to the form however, such as document.getElementById
var form = ...;
// Get the query string, stripping off the question mark (not strictly necessary
// as it gets added back on below but makes manipulation much easier)
var query = location.search.substring(1);
// Highly recommended that you validate parameters for sanity before blindly appending
// Now append them
var existingAction = form.getAttribute("action");
form.setAttribute("action", existingAction + '?' + query);
By the way, I've found that modifying the query string of the form's action directly can be hit-and-miss - I think in particular, IE will trim off any query if you're POSTing the results. (This was a while ago and I can't remember the exact combination of factors, but suffice to say it's not a great idea).
Thus you may want to do this by dynamically creating child elements of the <form> that are hidden inputs, to encode the desired name-value pairs from the query.
Related
I have a series of selector fields in a form. (The values of each selector are passed in to variables.) Once all fields are selected the submit button sends the user to the page with products sorted by a single category and multiple product characteristics using the www.mydomain.com/?product_cat=cat-name&characteristics=foo,bar,candy URL query.
The query works when I type it into the browser. When I try passing it through using jQuery it only passes the question mark (www.mydomain.com/?). If I remove the question mark then the rest of the string passes through. Am I using the wrong method? Here's my code:
jQuery(function($) {
$("#msform").submit(function() {
var homeType = $("#homeType").val(); //drop down selector value builds 1st part of category name
var eqType = $("#eqType").val(); // drop down selector value builds last part of category name
var sqType = $("#sqType").val(); // product characteristic value from drop down selector
var flowType = $("#flowType").val(); // prod char value
var locationType = $("#locationType").val(); //prod char value
var urlSet = "/?product_cat="+homeType+"-"+eqType+"&characteristics="+sqType+","+flowType+","+locationType; // URL I wish to send the visitor to after clicking submit button
$("#msform").attr('action', urlSet);
$("#msform").submit();
});
});
I have tried using ascii codes for the question mark. I have escaped the question mark but nothing seems to allow the whole string to pass to the URL.
below code is just a try, Its better to do ajax form submission
jQuery(function($) {
homeType = $("#homeType").val();
eqType = $("#eqType").val();
sqType = $("#sqType").val();
flowType = $("#flowType").val();
locationType = $("#locationType").val();
urlSet = "<?php echo home_url();?>/?product_cat="+homeType+"-"+eqType+"&characteristics="+sqType+","+flowType+","+locationType;
$("#msform").attr('action', urlSet);
$("#msform").submit(function() {console.log('submit success')});
});
I'm building a page for digital campaigns and I'd like to personalize the content of that page based on who referred users there.
For example, A sends B a link to this page, I generate the link to be sent by A automatically on his dashboard. When B clicks the link, I want the page title to say "Hey, A referred you here"
I know the solution to this might be simple but I'm not very awesome with web dev yet. How do I
Pass this information through the link?
Collect the information on the page and put it in as part of the content?
Looking forward to suggestions for most effective implementation
Theory
You can pass information to a page through the URL using URL parameters. This method of posting data is called GET
For example, take this URL:
example.com?key1=val1&key2=val2
You can send any number of parameters using the syntax key=value (note, value is not enclosed in quotes), and separate each one with an &. You must put a question mark between the URL and the parameters.
JavaScript
You can then retrieve the URL parameters using the following JavaScript code. Insert the following at the beginning of your page.
//To get Query Strings with JS
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
To get the value of a URL parameter, do the following:
var x = urlParams.key1; // x will be "val1"
PHP
To retrieve the URL parameters using PHP, it is much simpler. You don't need to add any code to the beginning of the page as with JavaScript, as it is an inbuilt feature of PHP. Just do the following:
$x = $_GET["key1"]; // $x will be "val1"
Practice
In your case, you could make the URL show for user Albert, his unique URL for sharing could be
example.com?sender=Albert
And on your website you could put
<script>
if (urlParams.hasOwnProperty("sender")) {
document.write("Hey, " + urlParams.sender + " reffered you here!");
}
</script>
I'm new to jQuery and I am trying to understand a bit of code to be able to apply a similar concept in my coursework.
$(function(){
$(".search").keyup(function() {
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\') {
}
});
})(jQuery);
What is the dataString variable trying to do?
There are quite a few things that seem "off" with this snippet of code, which I'll address below.
What is this code doing?
It looks like some basic functionality that might be used to build a search querystring that is passed onto some AJAX request that will search for something on the server.
Basically, you'll want to build a string that looks like search={your-search-term}, which when posted to the server, the search term {your-search-term} can be easily identified and used to search.
Noted Code Issues
As mentioned, there are a few issues that you might want to consider changing:
The Use of Escaped Quotes (i.e. \') - You really don't need to escape these as they aren't present within an existing string. Since you are just building a string, simply replace them with a normal ' instead. Without knowing more about your complete scenario, it's difficult to advise further on this.
Checking String Length - Your existing code once again checks if the searchId is an empty string, however you may want to consider checking the length to see if it actually empty via searchId.length != 0, you could also trim this as well (i.e. searchId.trim().length != 0).
Consider A Delay (Optional) - At present, your current code will be executed every time a key is pressed, which can be good (or bad) depending on your needs. If you are going to be hitting the server, you may consider adding a delay to your code to ensure the user has stopped typing before hitting the server.
You can see some of these changes implemented below in the annotated code snippet:
// This is a startup function that will execute when everything is loaded
$(function () {
// When a keyup event is triggered in your "search" element...
$(".search").keyup(function () {
// Grab the contents of the search box
var searchId = $(this).val();
// Build a data string (i.e. string=searchTerm), you didn't previously need the
// escaping slashes
var dataString = 'search=' + searchId;
// Now check if actually have a search term (you may prefer to check the length
// to ensure it is actually empty)
if(searchId.length != 0) {
// There is a search, so do something here
}
}
}
From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)
I'm really new to Javascript and I'm having some trouble understanding how to get the following to work. My goal is to have a certain Javascript action execute when a page loads and a variable added to the end of the URL would trigger which Javascript action to execute. The URL of the page that I'm looking to implement this on is http://www.morgantoolandsupply.com/catalog.php. Each of the "+expand" buttons, which are Javascript driven, drop-down a certain area of the page. Ultimately, I would like to be able to create a URL that would automatically drop-down a certain category when the page loads. Could anybody explain to me the process to do this? Thanks in advance for any help!
You have to parse the URL somewhat "manually" since the parameters in the url aren't automatically passed to javascript, like they are in server-side scripting (via $_GET in PHP, for instance)
One way is to the use the URL fragment identifier, i.e. the "#something" bit that can go at the end. This is probably the neatest way of doing it, since the fragment isn't sent to the server, so it won't be confused with any other parameters
// window.location.hash is the fragment i.e. "#foo" in "example.com/page?blah=blah#foo"
if( window.location.hash ) {
// do something with the value of window.location.hash. First, to get rid of the "#"
// at the beginning, do this;
var value = window.location.hash.replace(/^#/,'');
// then, if for example value is "1", you can call
toggle2('toggle' + value , 'displayText' + value);
}
The URL "http://www.morgantoolandsupply.com/catalog.php#1" would thus automatically expand the "toggle1" element.
Alternatively, you can use a normal GET parameter (i.e. "?foo=bar")
var parameter = window.location.search.match(/\bexpand=([^&]+)/i);
if( parameter && parameter[1]) {
// do something with parameter[1], which is the value of the "expand" parameter
// I.e. if parameter[1] is "1", you could call
toggle2('toggle' + parameter[1] , 'displayText' + parameter[1]);
}
window.location.search contains the parameters, i.e. everything from the question mark to the end or to the URL fragment. If given the URL "example.com/page.php?expand=foo", the parameter[1] would equal "foo". So the URL "http://www.morgantoolandsupply.com/catalog.php?expand=1" would expand the "toggle1" element.
I'd perhaps go for something more descriptive than just a number in the URL, like, say use the title of the dropdown instead (so "#abrasives" or "expand=abrasives" instead of "#1" or "expand=1"), but that would require a little tweaking of your existing page, so leave that for later
You've already got the function to call: toggle2(), which takes two parameters that happen to be identical for all categories except for a number at the end. So create a URL that includes that number: http://www.morgantoolandsupply.com/catalog.php#cat=4
Then find that number in location.hash using a regular expression. This one is robust enough to handle multiple url parameters, should you decide to use them in the future: /[\#&]cat=(\d+)/. But, if you expect to never add anything else to the url, you could use a very simple one like /(\d+)/.
Once you've got the number, it's a simple matter of using that number to create your two parameters and calling toggle2().
This should work:
window.onload = function() {
if (/[\#&]cat=(\d+)/.test(location.hash)) {
var cat = parseInt(RegExp.$1);
if (cat > 0 && cat < 13) {
toggle2("toggle"+cat, "displayText"+cat);
}
}
}
Not a complete answer ("Give a man a fish" and all that), but you can start with something along these lines:
// entire URL
var fullURL = window.location.href;
// search string (from "?" onwards in, e.g., "www.test.com?something=123")
var queryString = window.location.search;
if (queryString.indexOf("someParameter") != -1) {
// do something
}
More info on window.location is available from the Mozilla Developer Network.
Having said that, given that you're talking about a PHP page why don't you use some server-side PHP to achieve the same result?