Javascript & doesn't append next parameter value pair - javascript

I am trying to append multiple parameter value pairs to a url for an ajax request. I know that this is supposed to be done using & instead of &. Why then, does the first function work and the second one fails?
function accountByName(firstName, lastName, resultRegion) {
var baseAddress = "Bank";
var data = "firstName=" + getValue(firstName) + "&lastName=" + getValue(lastName);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
function accountByName(firstName, lastName, resultRegion) {
var baseAddress = "Bank";
var data = "firstName=" + getValue(firstName) + "&lastName=" + getValue(lastName);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
When I do print statements in the serverside java code the firstName variable prints fine, but the lastName variable always comes back null when I use & Both variables print fine when I just use &, but I know this is not correct XML.

So here's what your instructor meant:
In an (X)HTML page if you have something like:
Link
You should use (even though it really doesn't make a difference except to the validator)
Link
That is the ONLY time you should use an & in a query string.

You are incorrect: you are not supposed to use & as the parameter separator in a URL. The first function constructs the URL:
Bank?firstName=foo&lastName=bar
The second:
Bank?firstName=foo&lastName=bar
The 1st URL has two parameters: firstName and lastName with the values foo and bar.
The 2nd URL has two parameters: firstName and amp;lastName with the values foo and bar. (Note: I believe the second parameter name is invalid and am not sure how it'd be parsed in Java; it may be library/server dependent)
Your Java code fails printing the lastName parameter in the second case because in that case it is not set.
Your confusion seems to stem from a misunderstanding of the URL format. The URL format is unrelated to XML or HTML. It is completely separate from the two. & is an XML/HTML entity. Were the URL some form of XML, you would be correct. However, as it is not one should not expect it to follow the rules and standards of XML.

You're creating a URL, not some XML content. You have to think about what system is going to be paying attention. An XML/HTML parser is never going to look at that URL you're creating. The server, however, will certainly be interested in interpreting the URL as a URL. The XML entity syntax & is completely alien to something parsing a URL.

Related

Javascript get query string parameter values that has query string parameter in turn

I am pretty poor in regex so hoping to get some help here.
I have an url which has a query string parameters. The parameter in turn is a url which has qs parameters of itself.
For eg: my url is something like
http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true
Now when i use any of the functions to extract the whole query string parameter, i somehow get only the first one.
What i am expecting is: : /en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true
But what i get is: /en-us/products-overview/find-product/home/kitchen/2980?source=google
notice that the other two parameters (isadvertisement and organic) are missing.
my function is
function getUrlParameter(name) {
var url = 'http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true';
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(url);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
JsFiddle here:
i tried other links from SO to extract QS parameters. none of them seem to handle this scenario
The ampersands in your url are being treated as top level parameter separators. If they are part of a parameter themselves, they need to be escaped. Your escaped url would look like http://myurl.com/somepage?ref=%2Fen-us%2Fproducts-overview%2Ffind-product%2Fhome%2Fkitchen%2F2980%3Fsource%3Dgoogle%26isadvertisement%3Dfalse%26organic%3Dtrue. How you encode the url depends on where it is coming from. JS provides the encodeURIComponent() function.
Then you could use decodeURIComponent() to decode that back to the expected url. The issue is coming from having nested query parameters.
To get query parameters in general though, a built in solution using URL could be something like:
var url=new URL('...');
for (var e of url.searchParams.entries()){
console.log(e);
}

Passing variable via query string truncates plus symbol

I am wondering how to pass a variable in Javascript as +4 and then retrieve it as +4 in php.
No matter what I do, whenever I store a +4", and verify its being stored as such, when I retrieve it the + is gone and all I get is the number (i.e. 4).
Here's what I've got:
file.js
var testString = "+4";
console.log(testString);
window.location.href = "file.php?testString=" + testString;
OUTPUT: +4
file.php
$testString = $_GET["testString"];
echo $testString;
OUTPUT: 4
I know I can always append the "+", but that just seems like an extra process that shouldn't be necessary; I'd rather pass the variable properly.
You need to encode your parameters:
var testString = "+4";
console.log(testString);
window.location.href = "file.php?testString=" + encodeURIComponent(testString);
There's a few questions/resources that can help you understand why this is required:
Why do you need to encode URLs?
Encoding URL's via lifewire
Introduction to URL encoding
The developer documentation

Encoding URL (including characters like &) using jquery or native javascript function?

I have one one hidden paramter in form whose value is
custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
I want to encode it before sending it and so that characters like & can be replaced with %26 etch
i tried using javascript built-in encodeURI("urlToencode") but does not encode characters like &?
Try this code line,
encodeURIComponent("fisrtName=scott&lastName=Miles");
Use https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
You need to call that on each dynamic part (name and value) of the URL query string. So the question is what is the URI component in custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles That doesn't really look like a URL because you have the = before the ?
The most sense that I can make is that the full URL is something like
http://myserver/file.do?custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
In which case, you should build your URL like
var custAddress = "CustomerAddress.do?fisrtName=scott&lastName=Miles";
var initialPath= "/path/to/file.do?";
var url = initialPath + "custAddress=" + encodeURIComponent(custAddress);
Since you mentioned jQuery, you can use a $.param, looks cleaner and does the encoding for you, and you can give it multiple query parameters at once
var url = initialPath + $.param({
custAdrress: custAddress,
otherParam: "paramVal",
// Both the param name and value need to be encoded and $.param does that for you
"funny Name & Param": "funny & value ="
});

Updating multiple parameters in a groovy string from a javascript function

OK, I'm a javascript/grails novice and I'm not sure what to do here.
Basically I have a javascript function that is being called with multiple parameters and I want to substitute them into a grails parsable string.
I have a number of grails drop downs that call a javascript function to link to another page with multiple parameters that need to be passed (item number and quantity).
Here is the select:
<g:select optionKey="key" optionValue="value" value="${item.getQty()}" name="qty" from="[1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9]"
onchange="goToPage('qty${item.id}',this.value)"></g:select>
The javascript function:
<script type="text/javascript">
function goToPage(itemId, val){
window.location.href="${createLink(controller:'GOrder' ,action:'updateShoppingCart' params:[item: "", qty: ""])}" + itemId + val;
}
So, it takes the itemId and val, concats them and replaces the last set of quotes with that concatenated value. What I want to happen is for each of the parameters to replace one of the sets of quotes.
I really don't understand how what looks like concatenating a string actually substitutes a value.
Thanks!
You're getting your server and client sides mixed up here. The
${createLink(controller:'GOrder' ,action:'updateShoppingCart' params:[item: "", qty: ""])}
is evaluated by Grails on the server side when rendering the GSP into HTML, so what you end up with in your JavaScript will be something like
function goToPage(itemId, val){
window.location.href="/myapp/GOrder/updateShoppingCart?item=&qty=" + itemId + val;
}
What you probably want instead is to generate just the base URL up to the question mark on the Grails side, then add the query parameters on the client side in JavaScript
function goToPage(itemId, val){
window.location.href=
"${createLink(controller:'GOrder', action:'updateShoppingCart'
).encodeAsJavaScript()}?item=" + encodeURIComponent(itemId)
+ "&qty=" + encodeURIComponent(val);
}
Note the way I've added encodeAsJavaScript() - you should always use this when generating values that are to be included in a JavaScript string literal, it will backslash-escape anything that needs it. Similarly any JavaScript string you're adding to a URL needs to be encoded using the JavaScript encodeURIComponent function - if the value of itemId were "item one", for example, you need to append item%20one to the URL.

How to Execute Javascript Code Using Variable in URL

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?

Categories