Add # and ! to URL plus text from submitted search form - javascript

I need submitted text added to a URL from a search from. I found some code here Add text to parameter before sumbit form , which partially works but some of the text I need added includes #! and ? which translates to %23%21 and %3F when added to the url.
Code from stack overflow (best answer):
<form action="http://example.com/search" method="get" onsubmit="return addText();">
<input type="text" name="q" id="q">
<input type="submit">
</form>
<script>
function addText(){
document.getElementById("q").value += " BBBB CCCC"; // Whatever your value is
return true;
}
</script>
My URL needs to return something like this:
http://example.com/?search=TEXT#!summaryList?skipMake=true&skipModel=true
The url up to TEXT comes through (TEXT is the q value submitted from the form), but the #! before summary and ? before skip do not and the whole string is needed for the URL to function correctly.
Is there an easy way to make it work using the code above or would I be better off finding a PHP script?
Thank you!

Use encodeURIComponent() to encode your URL (to format #):
encodeURIComponent(myUrl)
Use decodeURIComponent() to decode your URL:
decodeURIComponent(myUrl)
var myUrl = 'search=TEXT#!summaryList?skipMake=true&skipModel=true';
console.log('Encode URL', encodeURIComponent(myUrl));
console.log('Decode URL', decodeURIComponent(myUrl));

Anything after # is not sent to the server. If you need to send it to the server, you will need to place it in it's own parameter (I used extra as the name). You will then need to also make sure that it is encoded properly, otherwise it could send that data as key/value as well.
http://example.com/?search=TEXT&extra=summaryList%3FskipMake%3Dtrue%26skipModel%3Dtrue
On your server side, you will then need to decode it, and grab the key/value pairs

Related

How do you pass a Javascript variable through POST to use in Flask?

So I have a JS variable that is created after pressing a button, and I need to pass it to my app to process in flask. I'm currently trying to do it with query strings but I'm not really sure what I'm doing.
In the html I have a form set up like this:
<form action="/deleteBook" method="POST" onsubmit="deleteBook()">
<input type="submit" value="Delete" />
</form>
which calls this function to apply query string:
function deleteBook() {
var existingUrl = window.location.href;
window.location.href = existingUrl + '?itemID=' + itemToRemove;
};
and then I want to process that variable through flask:
#app.route('/deleteBook', methods=["POST"])
def deleteBook():
if(request.method == "POST"):
itemID = request.args.get('itemID')
In my mind the code should detect the form submission (basically single button click), call deleteBook() which should then append a query string to the URL which can then be processed in flask.
I'm aware that I'm lacking some basic knowledge about html/js/processing data so I'm not really sure where to go from here. Should I use PHP to process the request somehow? Or should I not be using a form at all? Or maybe in flask there is an easier way to get data without using POST? I'm not sure so any suggestions are appreciated, thanks!
Well I for one find your style for a question like this unique so I'll try my best to explain my idea of the answer.
Firstly, I would just have the form calling the function
Secondly, I would have the function call an 'XMLHttpRequest' with 'POST' configuration
The HTML
<form onsubmit="deleteBook()">
<input type="submit" value="Delete " />
</form>
The JavaScript
function deleteBook () {
var xhr = new XMLHttpRequest();
xhr.open('POST', existingUrl + '?itemID=' + itemToRemove, true); //The second argument is the url you wish to 'POST' to
xhr.send(); //if you want to do something if your flask returns something, 'xhd.onload = function () {}'
}

form.submit() truncating string with '?'

I have a JavaScript function :
function post(aAction) {
var form = document.createElement("form");
form.action=aAction;
document.body.appendChild(form);
form.submit();
alert(form.action);
}
( I'm an experienced developer but not much experience with JScript - lifted that post() function from some website. )
I am passing this string into the function: A URL with query information:
http://testServer:3072/aQuerySite.dll/GetErrors?server=server1:5678
This URL returns a page listing error messages from the specified server: "server1:5678" - an argument passed to a server side query as
server=server1:5678
in the URL.
If I paste that URL directly into a browser and post it, the correct page with appropriate data is returned, and the browser address shows the complete URL as it was sent.
But when I pass the URL into my function, I get back a correctly formatted page but no records, and the browser address shows the URL truncated after the ? token : http://testServer:3072/aQuerySite.dll/GetErrors? The page returns showing no records because the query parameters after ? never got to the server for evaluation - query runs looking for nothing.
alert(form.action) in the function, which I added for debugging, shows the correct URL with query arguments, as does my debugger (WebStorm) and as mentioned, if I hit the URL directly from the browser, I get the correct result. I can only conclude that my URL is getting truncated in the form.submit() call.
This happens in IE, FireFox and Chrome. I also tried using ? for "?" - same result.
Why is this happening? How can I fix it?
It seems like you're trying to use a newly created form to redirect a user through its submission.
That is not necessary, as you can simply redirect the user using the following:
window.location = 'your_url';
In your case, you say that the querystring is being replaced with a simple ?.
That's because you created a form, and this form uses GET to post its data.
So if the form action is https://www.stackoverflow.com, the query string will be added with a interrogation following by the key/value pairs.
Let's suppose you have a form with two inputs named a and b, when you submit them, the query string would look like this:
https://www.stackoverflow.com?a=zzz&b=zzz
If you simply put this url in your form action, it will replace the query string with its own data when you submit it. Since your form has no named inputs, the query string will be empty, that's why you have an empty ? after the url.

I am using the OWASP ESAPI encodeForHTMLAttribute however symbols are displaying as their html entity number instead of symbol

I am just learning about the OWASP ESAPI for XSS prevention and I am using the Javascipt version within my app
According to Rule #2 in the XSS prevention cheat sheet you should "Attribute Escape" before inserting untrusted data into attribute values like "width, name or value" and I am working on this at the moment.
However when using encodeForHTMLAttribute() before inserting an email address as a value of an input field in a contact form, the # symbol is displaying as it's corresponding html entity #&x40; as you can see in this screenshot image:
Am I missing something?
I have made sure the charset of the document is set to utf-8 as follows:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
I have also added in the accept-charset="UTF-8" Attribute to the form in question.
HTML form:
<form id="contact_form" name="contact_form" method="post" action="" accept-charset="UTF-8">
<div class="form_divider">
<label for="contact_form_email"><span class="asterisk">*</span>E-mail</label>
<input id="contact_form_email" tabindex="1" name="contact_form_email" type="email" data-role="none" maxlength="254" placeholder="E-mail" required/>
</div><!--/form_divider-->
</form>
Data flow of my app:
Within my app, an ajax request is performed to submit the login details and after successful authentication, I retrieve their details from the database and send back to the client side in json format.
I then insert these details to the html where applicable
Javascript:
$.ajax({
url: app_root_url + 'login_registration/user_processing.php',
data: JSON.stringify(params),
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function(data){
//data will be the user details such as userID, display name, email
var result = data;
prepareAppAfterLogin(result);
}
});//end ajax
function prepareAppAfterLogin(result){
var userDetails = result.userDetails;
generateUserProfilePage(userDetails);
}
function generateUserProfilePage(userDetails){
var userID = userDetails.userID;
var display_name = userDetails.display_name;
var email_address = userDetails.email_address;
var profile_image = userDetails.profile_image;
$("#profile_pic").attr('src', profile_image);
var safe_email_address_for_html = $ESAPI.encoder().encodeForHTML(email_address);
$("#profile_email_address").html(safe_email_address_for_html);
var safe_email_for_attribute = $ESAPI.encoder().encodeForHTMLAttribute(email_address);
$("#hidden_input_for_email").val(safe_email_for_attribute);
$("#contact_form_email").val(safe_email_for_attribute);
}
Edit:
I have just found documentation that supports what #Cheran Shunmugavel said in his comment below:
Rule #2 here: https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
"It is important to note that when setting an HTML attribute which does not execute code, the value is set directly within the object attribute of the HTML element so there is no concerns with injecting up."... "The appropriate encoding to use would be only JavaScript encoding to disallow an attacker from closing out the single quotes and in-lining code, or escaping to HTML and opening a new script tag."
following this rule I have just tried to encode the email address for Javascript instead of encoding for html attribute as follows:
function generateUserProfilePage(userDetails){
var safe_email_address = $ESAPI.encoder().encodeForJavaScript(userDetails.email_address);
$("#contact_form_email").val(safe_email_address);
}
However it seems doing this also creates display problems:
Can you confirm do I need to javascript encode here? thanks
The encodeForHTML and encodeForHTMLAttribute functions are not necessary if you are using the jQuery val method to insert the data in the document. I can't find anything in the official documentation, but there is a good explanation on this StackOverflow question: Do jQuery's val() and prop() methods html-escape values?. The important takeaway is that val sets the DOM value property internally, and that property will never attempt to interpret text as HTML markup, so escaping is not necessary.

Performing form action via submit button depending on the '<a>' link chosen from another different page using javascript

There are 4 different HTML pages namely: "HomePage.html", "ABCpage.html", "Page1.html" & "Page2.html".
HomePage.html - In this page there are 2 links both when clicked are redirected to 'ABCpage.html'. The following is the HTML code below.
<body>
Page 1
Page 2
</body>
ABCpage.html - In this page there is only an input button named 'Enter', which when clicked should redirect either to "Page1.html" or "Page2.html" depending on the link choosed from "HomePage.html"
<body>
<form method="post">
<input type="submit" id="submit" value="Enter" />
</form>
</body>
"Page1.html" and "Page2.html" are just blank pages.
So what should I do to redirect from "ABCpage.html" to either "Page1.html" or "Page2.html" depending on the links chosen from "HomePage.html". Now I am purely using javascript for client side scripting and JSP for server side scripting and am not familiar with jquery. Now the link that I choose from "HomePage.html" should directly affect the form action in "ABCpage.html" for redirecting it further either to "Page1.html" or "Page2.html" depending on the link chosen. So what could be the javascript code for the following as I am finding it hard to get a solution for this.
You will need to pass query string params from the first page. So the href values on the links on the homepage should look more like this:
ABCpage.html?page=2
ABCpage.html?page=1
Then on the ABCpage.html you will need to parse the query string params from the URL using javascript and append them to your form action. The logic in your JS would read the query string params and determine the form action based on some basic conditional statements.
Here is a function you can use to retrieve the querystring param once you are on the ABCpage:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
credit: How can I get query string values in JavaScript?
You need to remember the user choice. There are many ways to do it like using a cookie, local storage API or simply passing it by url.
The last is the simplest in my oppinion and you can do it basically in two ways:
a) By passing it as an url parameter that can be read server side which enables server to serve actually distinct pages even the only difference happening to be the form action url. That is:
Link1 = abcPage.html?id=1
Link2 = abcPage.html?id=2
b) By using the hashurl, that is not readable server side and then you really need to rely in javascript to read it (and detect its change if you want) from the location object.
Link1 = abcPage.html#1
Link2 = abcPage.html#2

Send a user to a certain URL depending on his text field input

Basically I want the ff. done:
User inputs a text in my text field. If his text matches a text in my "list," he is sent to a certain URL once he hits the submit button.
I found a similar code on this site but his is just one specific text value. [ Get input text field from HTML into JavaScript and go to URL ]
I want mine to determine the user's text input from a list I provide. My list will have a lot of texts/urls and it will continue to grow, so manually inputting values into the script won't work for me.. I want to be able to edit the list (possibly in an admin panel or something?) instead of the js code.
Example:
input text: aaaa, go to URL1
input text: mmne, go to URL2
input text: lhfj, go to URL3
input text: tigf, go to URL4
input text: gred, go to URL5
Can anyone help me with this please? Thanks!
Hope this helps you
var Something =$("#TextBoxID").val();
if(Something == "aaaa")
{
window.location.href = 'URL1'; //Will take you to URL1
}
......
......
if you want to configure the list on an admin console you need to have some kind of server side technology like php (or node.js if you want to keep using javascript). You need to think of where this data will be stored. A possibility would be fetching the list of text/url pairs using ajax (e.g. with jQuery) and storing the data in some database or in your case also a plain text file probably would suffice. The functionality you are looking for is not possible with plain HTML and JavaScript on cient side.
Use a function like this, if you store your URLs on the client side (HTML/JS page):
function determineAndGoToURL(text) {
var url = "#";
switch(text) {
case "aaaa":
url="www.google.com";
break;
case "bbbb":
url = "www.bing.com";
break;
default:
url = "www.yahoo.com";
break;
}
window.location.href = "http://" + url;
}
If you have an updated list of URLs on the server side, get them from server-side to client side, and iterate over them with a for statement.
I'd suggest, you'd get them from the server as JSON, and use JSON.parse(text) to create an object out of them, and then iterate.

Categories