Passing variable via query string truncates plus symbol - javascript

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

Related

passing mixed string and int parameters to javascript

I've had a look around and can't seem to find a working solution, so here's the requirements.
I'm building a system that takes data from a master page and loads it into a modal style window for quick data processing. I have a javascript function passing 4 status parameters, and whilst 3 of them will always be integers, one of them can be integer or string.
The function works if all 4 parameters are integer, but fails when a string is passed.
function passJob(jobid,equipid,status,location) {
var a = document.getElementById('jobnumber');
var b = document.getElementById('equipid');
var c = document.getElementById('status');
var d = document.getElementById('location');
a.value = jobid;
b.value = equipid;
c.value = status;
d.value = location;
}
PHP
<a href='#' onclick='passJob($sr,$eid,$ss,$sl);'>Modify Job</a>
$sr, $ss and $sl will always be numeric, $eid will either be integer, or a string starting with M and then having a number after it.
I've tried adding quotes to the variables, around the variables, inside the function etc and no luck :(
You need to pass as string if you do not know what they are - also make sure you do not nest the same type of quote:
onclick='passJob($sr,"$eid",$ss,$sl);'
Just wrap it in quotes. This treats it like a string at all times to avoid any potential JavaScript parsing errors.
Modify Job
That is because you do not properly encode the variables in a Javascript notation. Try:
echo "<a href='#' onclick='passJob(".json_encode($sr).",".json_encode($eid).",".json_encode($ss).",".json_encode($sl).");'>Modify Job</a>";
Do like below
Modify Job

Passing in a key results in extra characters in my firebase URL, how do I remove them?

When placing the "key" variable inside of this string, it displays 'simplelogin%3A5' instead of 'simplelogin:5'. Is there a way to just pass in the latter?
var populateTasks = function(date, key){
$scope.ref = new Firebase("https://myfirebase.firebaseio.com/users/"+key+"/tasks");
};
results in: https://myfirebase.firebaseio.com/users/simplelogin%3A5/tasks
I need: https://myfirebase.firebaseio.com/users/simplelogin:5/tasks
var uri = "//what you need to convert";
var uri_dec = decodeURIComponent(uri);
var res = uri_dec;
Where does the value of key come from? If you get it from a URL, it makes sense that you see %3A.
A : has a special meaning in a URL, so it is escaped. And the URL escape sequence for a : is %3A.
To convert the %3A back to : you simply unescape it like this:
unescape(key)
Or use decodeURIComponent, which in this case accomplishes the same. The best way to decode the value depends on why it was encoded in the first place, hence my initial question.
Have you tried trimming key before concatenating it to the URL?
key = key.trim();

Javascript & doesn't append next parameter value pair

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.

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 ="
});

regex parsing a dynamic parameter from url string

I have a URL as follows: www.mysite.com?paramNamePrefixXXX=value
What is the best way to parse the url for the parameter name / value where XXX is dynamic/unknown..
Since I don't know the parameter name at render time.. I'd like to match on the 'startswith.. 'paramNamePrefix' + XXX (where XXX is some string..) and return the value
jquery offer a simple way to do this?
var url = "http://www.mysite.com?foo=bar&paramNamePrefixXXX=value&fizz=buzz",
prefix = "paramNamePrefix";
var desiredValue = url.match(new RegExp('[?&]' + prefix + '.*?=(.*?)[&#$]', ''));
desiredValue = desiredValue && desiredValue[1];
console.log(desiredValue); // -> "value"
Demo
This will parse it I believe. The only issue you would run into with the way it's written is if there was an = sign in your parameter value somehow.
((?<=&|\?).+?)(?<=\=)(.+?(?=&|$))
basically I've got it in 2 reference groups
((?<=&|\?).+?) <-- captures parameter name using a look behind
(?<=\=)
(.+?(?=&|$)) <-- captures parameter value using a look ahead

Categories