Data passed to other pages via hyperlink is being cut off - javascript

I have a form that contains 2 <select>, the first select auto-populates itself upon page load, while the second select populates itself based on the choice selected in the first select.
To accomplish this, whenever the the select's state changes, the selected value in the first would be passed to a seperate page where it is used to populate the 2nd <select>
Problem
The selected value( Food & Beverages in this case) which is passed through the url is being cut off halfway, causing an incomplete string to be send to the processing page for the 2nd , which causes it to be unable to run.
Steps taken to identify the issue
I've echoed the values that is passed through the url and only got "Food", with the rest of the string cut off. I've tried replacing the string values to Food and Beverage, and the whole thing works perfectly, leading me to conclude that the string is being cut off due to the ampersand(&) sign which causes the computer to treat the part of the string after the ampersand as another value to be passed through the URL.However, as i did not assign it to a variable, it is not being passed through.
Question
Is there any way for me to pass the value without it being cut off?
Code Extracts:
Processing Page
<?PHP
include("cxn.inc");
$query=$cxn->prepare("SELECT * FROM `BusinessSubCategory` WHERE `BusinessCategory`=:businesscategory");
$query->bindValue(":businesscategory",$_GET['category']);
$query->execute();
$count=$query->rowCount();
if($count>0)
{
echo"<option id='subcategory' value=''>Please select a SubCategory</option>";
while($result=$query->fetch(PDO::FETCH_ASSOC))
{
$subcategory=$result['BusinessSubCategory'];
echo"<option id=$subcategory value=$subcategory >$subcategory</option>";
}
}
else
{
echo"<option id='subcategory' value=''>Error,fetch query not run. </option>";
}
?>
JQuery Code
$(document).ready(function(){
$('#BusinessCreateCategory').load('getbusinesscategory.php');
$('#BusinessCreateCategory').change(function(){
var category=$('#BusinessCreateCategory').val();
window.location.href='getbusinesssubcategory.php?category='+category;
});
EDIT:Tried encodeURIComponent, but the data is not being encoded as i can see from the url of the processing apge that it is cut off at the ampersand.HOWEVER, if i were to manually enter the url as a string and then code it using encodeURIComponent, it works wonderfully.CAn anyone shed some light on why i am unable to encode $('#BusinessCreateCategory').val(); ? Thanks!
E.gThis works
var category="Food & Beverages";
var encoded =encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
E.g This does not
var category=$('#BusinessCreateCategory').val();
var encoded= encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
If it helps, the data i am trying to pass through the url is taken from my database.

You need to encodeURIComponent the value for category before using it in a URL.
$('#BusinessCreateCategory').change(function(){
var category=$('#BusinessCreateCategory').val();
var encoded = encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
});
Ampersand is a special character that garbles the URL you are trying to pass. Encoding the value should allow you to treat it as a single value.

There is a browser limit to how many characters can pass through. Do you have an example of the complete string that you are trying to pass? I would initially suspect that this could be an encoding issue.

encodeURIComponent to encode the string being passed.
The value should be encoded but when you query your db it might look for exact match, in case you fail to see any output via the encoded string use decodeURIComponent to decode the string before passing it to db. Check the output at phymyadmin before your formally put the code.

Related

Remove last 3 letters of div (hidde also in browser page source)

this is my HTML
<div id="remove">Username</div>
and this is my JS code
function slice() {
var t = document.getElementById("remove");
t.textContent = t.textContent.slice(0, -3);
}
slice();
Username load from foreach
{foreach from=$last_user item=s}
{$s.date}
{$s.username}
{/foreach}
This code working and remove 3 letter but when right click on browser and look at page sources i can see "Username" !
I need remove three letter because of privacy and security .
something like
*** name or usern ***
Thank for help me !
The only secure way to make sure the client can't see a particular piece of information is to never send it to the client in the first place. Otherwise, there will always be a way for the client to examine the raw payloads of the network requests and figure out the information they aren't supposed to know.
You'll need to fix this on your backend - either hard-code in
<div id="remove">Usern</div>
or, for a more dynamic approach, use a template engine (or whatever's generating the HTML) and look up how to change strings with it. For example, in EJS, if user is an object with a username property, you could do
<div id="remove"><%= user.username.slice(0, -3) %></div>
Changing the content only with client-side JavaScript will not be sufficient, if you wish to keep some things truly private.
With Smarty, you can define a modifier that takes a string and returns all but the last three characters of it.
function smarty_modifier_truncate_three($string)
{
return substr($string, 0, -3);
}
and then in your template, replace
{$s.username}
with
{$s.username|truncate_three}
If you want only the first three characters, it's easier because you can use the built-in truncate.
{$s.username|truncate:3}
JS doesn't change the source, it can only change the DOM, so what you can do is to keep the element empty and add a value to it using js, but don't forget that js runs on the client's side so its better here to send the string from the server without the last 3 characters.

Cookie based on page path

Is it possible to set a cookie value, as the url page path?
i.e I have a cookie that is set when someone clicks a button with the ID mybtn but I'd like the value of the cookie to be automatically generated based on the last part of the page path. For example if the user clicked the button whilst on a page www.myweb.com/cars/car1 the value of the cookie should be set as car1. The code below is where I've got to so far, but it's the "THEPAGEPATH" where I'm stuck as I guess I need to use javascript to pull the url information.
<script>$("#mybtn").bind("click", function() {
document.cookie="model=THEPAGEPATH;path=/;"
});</script>
Simple solution would be to just split the string, and take the last part of it.
<script>$("#mybtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str)
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
This works for both routes with and without trailing slash. It does not work for routes that have query parameters that contains slashes. If you need to support that, you could split the string on ?, and the use the same logic on the first part of the string.

Javascript crashes on special characters from query string

To use this value in my TypeScript I am getting it from my query string like this:
var UserName = #Request.QueryString["UserName"];
But I get a Unexpeted Identifier error on it because if in DevTool if I go to where it breaks that query string has a value like this:
var UserName = ANT -- ANT 37690 / THIRD PARTY
So is there a way to do some kind of sanitation on it so it wouldn't crash? I guess there are illegal characters in that value for JS?
The error has nothing to do with "special" characters, but with the fact that the right side of the assignment - unwrapped in quotes - contains what js engine views as unknown identifier[s].
One way to properly format data that becomes part of javascript code is to use JavaScriptSerializer class from System.Web.Script.Serialization namespace.
var UserName = #new System.Web.Script.Serialization.JavaScriptSerializer().Seria‌​lize(Request.Query‌​St‌​ring["UserName"]);
The shorter version of this for a string is:
var UserName = "#System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"])";
or overloaded version that wraps the result in double quotes:
var UserName = #System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"], true);
You need to include quotes for the value.
var UserName = "#(Request.QueryString["UserName"])";
Otherwise the name will come through verbatim in your code and cause the problems you are seeing.
There is no need to protect against an attack vector here as the user can alter the page as they see fit at any time with a user script, and the QueryString is entered by them and only seen as a result by them in this scenario.
If there was a need to scrub the user input, it should be done prior to it actually reaching the view on server side. However, if still concerned about scrubbing output into a view in this type of scenario in general, it would be prudent to include an encode from razor's library.
var sanitizedJsVariable = "#System.Web.HttpUtility.JavaScriptStringEncode(model.VariableFromServer)";

How do I put SAFEARRAY (array of bytes) to HTML Hidden field

I'd like to get array of bytes from active-x component, store that in html-form input hidden field and then pass it to server via form-submit. How can I do that?
MIDL:
HRESULT Data([out, retval] SAFEARRAY(VARIANT) *pArray);
C++/ATL
STDMETHODIMP MyActiveX::get_Data(SAFEARRAY **pArray)
{
CComSafeArray<BYTE> arr;
for (int i = 0; i < 10; i++)
{
CComVariant a;
a = (BYTE)i;
arr.Add(a);
}
arr.CopyTo(pArray);
return S_OK;
}
Javascript:
$("#hiddenField").val(myActiveX.Data);
Browser tells me: type mismatch
Although I am not familiar with your exact situation, I have seen some similar situations before.
You are correct to put your data in a field using $('#hiddenField'). If you've put a name attribute on that field so that it becomes part of the HTTP submit, that part is good.
As for myActiveX.Data, I imagine that this is some sort of JavaScript object. Remember that only a string can be put into an HTML input; it does not hold binary data.
What I would do is put a breakpoint before $("#hiddenField").val(myActiveX.Data);
. Use the debugger keyword if you're not familiar with it. Run the code in your debugger and look at the structure of the value of myActiveX.Data. It probably has some sort of wrapper field.
Alternatively, if you don't have access to a good JavaScript debugger, try the following"
for(x in myActiveX.Data)
alert(x + ": " + myActiveX.Data[x]);
I'm assuming the C++ code is the server side code.
The best way to handle this is to serialise the SAFEARRAY. From there you can handle it in two ways.
Firstly, the serialisation. I've looked at MSDN and I think using LPSAFEARRAY_Marshal and LPSAFEARRAY_Unmarshal (with an optional IDispatch or IUnknown IID to specify the type, but the documentation doesn't say how it's used) or LPSAFEARRAY_UserMarshal and LPSAFEARRAY_UserUnmarshal to convert the SAFEARRAY to/from a serialised format.
Secondly, handling the data transfer.
Option 1: Save the serialised data on the server side and put a token representing the saved file into the hidden field.
Option 2: Use Hex, Base64, etc. to encode the data into a printable format and putting that data into the hidden field.
Either way, when you need to get the data back, just de-serialise it with the matching function.

window.open(), browser address bar, and jQuery url decode

I am passing values in a URL query string that are interpreted by JavaScript and used to fill out form elements. The user click a link on one page, is taken to another page which then decodes the values from the URL and populates the form fields.
To decode the URL, I am using the jQuery URL Decoder plugin.
This is the parameter being passed to window.open():
http://mydomain.com/whatever?EmailAddress=me%40privacy.com&YourName=joe%20schmo&CompanyName=TEXAS%20A%20%26%20M%20-%20LUBBOCK%2C%20TX
When I plug that URL into the online version of the decoder, it is properly parsed - the querystring parameters are in the .params object, properly decoded.
However, after the link is clicked when I examine window.location.href, I get this:
http://mydomain.com/whatever?EmailAddress=me#privacy.com&YourName=joe%20schmo&CompanyName=TEXAS%20M%20&%20M%20-%20LUBBOCK,%20TX
Which comes out of the URL decoder as a giant mess (i.e. not properly decoded IMO because the input is not properly encoded).
How do I (safely) get back to string that's properly interpreted by the URL decoder?
use a javascript function like this:
function urlencode(str) {
return escape(str)
.replace(' ', '%20') // or replace with '+'
.replace('#', '%40');
}
(I know you don't need the first replace but this is more complete... you can add more replaces as you need them or search for a full urlencode)

Categories

Resources