In the form below, I change the action attribute and submit the form. That works fine. What goes on is: if the current location is http://localhost/search/?mod=all and the search term is 14, the action will be changed to http://localhost/search/?mod=all&handle=14 and so will the url in the browser.
But the next time I try to search, since the url now is http://localhost/search/?mod=all&handle=14, I get http://localhost/search/?mod=all&handle=14&handle=15. It'll keep going on and on with each search term.
Any idea how I can retain the orginal url http://localhost/search/?mod=all through this all.
Here's the form:
<form method="GET" class="modForm" action="">
<input type="text" placeholder="Search" class="modSearchValue">
<input type="radio" name="text" value="text" class="text" title="Search">
</form>
Here's the jquery:
$('.modForm').submit(function(event) {
var $this = $(this);
var query = $this.find('.modSearchValue').val(); // Use val() instead of attr('value').
var locale = window.location;
if ($('.text').is(':checked')) {
query = '&text=' + query;
} else {
query = '&handle=' + query;
}
route = locale + query;
console.log(route);
if (query.length >= 1) {
// Use URI encoding
var newAction = (route);
console.log(newAction); // DEBUG
// Change action attribute
$this.attr('action', newAction);
//event.preventDefault();
} else {
console.log('Invalid search terms'); // DEBUG
// Do not submit the form
event.preventDefault();
}
});
There are few ways to do it. I would rather not mess with window.location and do something simpler:
<form method="GET" class="modForm" action="">
<input type="hidden" name="mod" value="all"> <!-- mod is a hidden variable -->
<input type="text" id="modSearchValue"> <!-- name not defined yet -->
<input type="checkbox" id="textOrHandle"> <!-- name not required -->
</form>
$(".modForm").submit(function() {
$("#modSearchValue").attr("name", $("#textOrHandle").is(":checked") ? "text" : "handle");
// let the form submit!
});
You have multiple ways to do it. Why can't you store original URL in a global variable (kept outside your functions like form submit etc.)
If you do not want that you can use window.location.hash which will return all the GET params you are sending. Using split you will be able to get exact parameter that you want. If you still need help, I will post the code.
Quickest solution: If, for this code, window.location should always be http://localhost/search/?mod=all, then you don't even need to say var locale = window.location. Just say var locale = "http://localhost/search/?mod=all" and you avoid the problem.
var s = window.location.hostname; // gets the hostname
var d = window.location.protocol; // gets the protocol
var g = window.location.search; // gets all the params
var x = g.split("&"); // split each parameter
var url = d+"//"+s+x[0]; // makes url you want
alert(url); // just for chill
Related
This is the job reference number I want to send to my form job reference textbox:
<p><span id="job" value="90192"><strong>Reference Number: 90192</strong></span></p>
//when this link will be clicked it will redirect to apply.html with job value stored in session.
Apply Here
<p><span id="job2" value="90192"><strong>Reference Number:90192</strong></span></p>
//when this link will be clicked it will redirect to apply.html with job value stored in session.
Apply Here
JavaScript file of jobs.js:
"use strict"
function storedata() {
var job = document.getElementById("job").value;
var job2 = document.getElementById("job2").value;
var job3 = document.getElementById("job3").value;
sessionStorage.job = job;
sessionStorage.job2 = job2;
sessionStorage.job3 = job3;
}
function init() {
var apply = document.getElementById("apply");
var apply2 = document.getElementById("apply2");
var apply3 = document.getElementById("apply3");
apply.onclick = storedata;
apply2.onclick = storedata;
apply3.onclick = storedata;
}
window.onload = init;
Here I want to store my job reference number which is from apply.html:
<label for="Job">Job Reference Number</label>
<input type="text" name="Student ID" id="Job" norequired="norequired" pattern="\d{5}" />
<br />
<br />
And this is my JavaScript function for getting the sessionStorage in apply.js:
function retrievedata() {
document.getElementById("Job").value = sessionStorage.Job = Job;
}
The issue is that when click on apply link from jobs.html it will redirect to apply.htm where the job reference number will be stored but it is not happening
Do like this
store data
sessionStorage.setItem("job", "xyz");
retrive
if (sessionStorage.job)
document.getElementById("result").innerHTML = sessionStorage.getItem("job");
Check this also : https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
The problem is you are using anchor tag href to navigate to the apply.html and hence before your method triggering on click gets executed it's going to the apply.html.
<a href='apply.html'>Button</a>
Use something like this
<a id='navigateToApplyPage'>Button</a>
In the JS:
$('#navigateToApplyPage').on('click',function(){
// set sessionstorage //sessionStorage.setItem....
// navigate to the required page // window.location.href = .....
})
Problem is how you are referencing value. There is no value property for non inputs.
var el = document.getElementById("t");
console.log("value: ", t.value); //nope
console.log("getAttribute: ", t.getAttribute("value")) //right
console.log("dataset: ", t.dataset.value) // how most would do it
<span id="t" value="1" data-value="123"></span>
Event better use data-value since that is a valid attribute.
And session storage keys are case sensitive sessionStorage.Job is not the same as sessionStorage.job And this line is wrong.
document.getElementById("Job").value = sessionStorage.Job = Job;
You are storing the variable Job into sessionStorage.Job which is storing Job into the value. It should just be
document.getElementById("Job").value = sessionStorage.job
And after that, you have to figure out what item you clicked.
I have a hyperlink which i am redirecting to a page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/Merging/Index/?workItemID=' + id;
});
My action in the controller page is
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID==null? 0: workItemID.Value) ;
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
return View(mergingVM);
}
So what it does is when i click on the hyperlink it redirects me to the merging page.
After redirecting to Merge page, the drop down fills with id(selected in home page) and correspondingly triggers the button click.
My issue When i reload the merge page the value in the drop down doesn't get clear. I.e if i have redirected from home page to merge page , then the drop down has some value. but when i refreshes it the selected value should go. I understand that the query string still holds the value. But is there any alternative to send parameter to action without using windows.location.href in jquery.
If you are using hyperlink then also you can try it
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
$(this).attr('href','/Merging/Index/?workItemID=' + id)
});
In order to clean the query string you should use redirect to another view.
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID == null ? 0 : workItemID.Value);
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
//to send this model to the redirected one.
TempData["model"] = mergingVM;
return RedirectToAction("CleanIndex");
}
public ActionResult CleanIndex()
{
var model = (MergingVM)TempData["model"] ?? new MergingVM();
// Do something
return View("Index", model);
}
To find alternatives to an send parameter to a method you first need to understand the model Bindding action.
The model bidding searches a value in:
Form Data
Route Data
Query String
Files
Custom (cookies for example)
If your action must need to be HttpGet you lose the Form Data which would be a nice alternative for you.
If I understand correctly... the below worked for me.
If there's an ID appended to the URL, it gets logged to the console as the variable "param". The URL is then replaced (so that if you refresh the page, the ID is removed from the URL).
$(document).ready(function() {
var url = window.location.toString;
var hostname = window.location.hostname;
var pathname = window.location.pathname;
var param = window.location.search;
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/new-page.php?' + id;
});
if ( pathname == "/new-page.php" && param ) {
console.log(param);
window.history.pushState("string", "Title", "http://yourURL.com/new-page.php");
//Do something with param...
}
});
This assumes that if there is no ID appended to the URL, the drop-down won't do anything. You also would need to update the URLs to the correct ones (I ran this on my local server).
I think you should use POST where you don't want to presist workItemID.
I mean all places where you have links you should use somethink like this:
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="1" /> <-- your Id
<input type="submit" value="Link to workItemID 1!" /> <-- your link
</form>
This way you will get your View but without workItemID in URL. But you should change css to make your POST link look like <a> tags.
Here is with your table:
#if (#Model.DataSetList[i].StateID == 43)
{
<td>
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="#Model.DataSetList[i].Workitem_ID" />
<input class="lnkMerging" type="submit" value="Merging" />
</form>
</td>
}
else
{
<td>
<text style="color:darkgrey" contenteditable="false">Merging</text>
</td>
}
You can save the parameter in local storage api of html5, and then use those parameters in Page load of index page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
localStorage.setItem("workItemID",id);
window.location = '/Merging/Index/;
});
On page load of index you can retrieve it using getItem
localStorage.getItem("workItemID"); and use it as per your requirement.
On page load of Merge page, you have to explicitly set the selected option like below and then remove the value from local storage.
$(document).ready(function(){
if(localStorage.getItem("workItemID")!=null){
$("#mydropdownlist").val(localStorage.getItem("workItemID"));
localStorage.removeItem('workItemID');
}
});
Make sure in var id = $(this).attr('data-id'); id should get same value as you have in the options on the merge page.
I need to remove query string value from the url once submit button is clicked. Can i able to do this with jquery?
Current Url:
siteUrl/page.php?key=value
After Page submit:
siteUrl/page.php
Actually i have landing to current page from another one with query string. I need query string value when page loads first time to prefill some details. But once i submitted the form, i need to remove query string value.
I have tried like this.
$('#submit').click(function(){
var newUrl = window.location.href.replace(window.location.search,'');
window.location.href = newUrl;
return false;
});
It makes changes in url as expected. but cant able to get the posted values.
Thanks in advance :)
How about this one. Hope it helps :)
$('#myform').submit(function(event){
event.preventDefault();
var currentURL = window.location.href ;
location.href = currentURL.substring(0, currentURL.indexOf('?'));
});
index.html
<form id = "myform">
<input type = "text">
<input type = "submit" id = "submit" value = "Send">
</form>
function getQueryString(url) {
return url.split("?")[0];
}
var Url=getQueryString("siteUrl/page.php?key=value");
console.log(Url);
You may try this for getting url
Unfortunately i cant able to do it with javascript or jquery. So i go through with php redirection, now it works.
<?php
if(isset($_POST['Submit'])) {
// actions
if(isset($_REQUEST['key']) && ($_REQUEST['key'] != "")) {
header('Refresh: 1;url='.$_SERVER['PHP_SELF']);
}
}
?>
Thanks all :)
There's a problem with my script. If I was to type something in with a spacebar, ie: google map it would change in input box: google+map what I don't like.
Also... When I submit again, it messes up more badly
<form name="input" action="" method="get">
Search: <input type="text" name="search">
<input type="submit" value="Submit">
<div id="result"></div>
</form>
--
$('form').submit(function() {
var form_data = ($(this).serialize());
window.location.hash = form_data.replace('=','/');
return false;
});
$(window).on('hashchange', function () {
var values = window.location.hash.slice(1).split('/');
$("[name=" + values[0] + "]").val(values[1]);
});
var values = window.location.hash.slice(1).split('/');
$("[name=" + values[0] + "]").val(values[1]);
You need to use decodeURIComponent to escape the value from the hash:
$('form').submit(function() {
var form_data = ($(this).serialize());
window.location.hash = form_data.replace('=','/');
return false;
});
$(window).on('hashchange', updateVal);
updateVal();
function updateVal() {
var values = window.location.hash.slice(1).split('/');
$("[name=" + values[0] + "]").val(decodeURIComponent(values[1]));
}
In this case FORM method 'GET' at <form name="input" action="" method="get"> should not be used.
According to W3 recommendation here
1.3 Quick Checklist for Choosing HTTP GET or POST
Use GET if: The interaction is more like a question (i.e., it is a
safe operation such as a query, read operation, or lookup). Use POST
if: The interaction is more like an order, or The interaction changes
the state of the resource in a way that the user would perceive (e.g.,
a subscription to a service), or The user be held accountable for the
results of the interaction.
In the GET the data is sent in URI and there is no spaces in URI and hence the problem.
However, if you need to use GET request for this then use decodeURIComponent to decodeURIComponent(values[1]) to escape the value
<html>
<head>
<script>
function open_win()
{
window.open("http://localhost:8080/login","mywindow")
}
</script>
</head>
<body>
<input type="button" value="Open Window" onclick="open_win()">
</body>
</html>
Hi ,
On click of a button , i am opening a new website (My web site )
I have two text fields ( One Text Field and another Password Field) , i am trying to send this values to the other opened window .
But its not working as I want.
I have tried the following ways
1. window.open("http://localhost:8080/login?cid='username'&pwd='password'","mywindow")
2. window.open("http://localhost:8080/login","mywindow")
mywindow.getElementById('cid').value='MyUsername'
mywindow.getElementById('pwd').value='mypassword'
Could anybody please help me if this is possible or not ??
Sorry for the incomplete details , its a Post request .
if you want to pass POST variables, you have to use a HTML Form:
<form action="http://localhost:8080/login" method="POST" target="_blank">
<input type="text" name="cid" />
<input type="password" name="pwd" />
<input type="submit" value="open" />
</form>
or:
if you want to pass GET variables in an URL, write them without single-quotes:
http://yourdomain.com/login?cid=username&pwd=password
here's how to create the string above with javascrpt variables:
myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");
in the document with that url, you have to read the GET parameters. if it's in php, use:
$_GET['username']
be aware: to transmit passwords that way is a big security leak!
Please find this example code, You could use hidden form with POST to send data to that your URL like below:
function open_win()
{
var ChatWindow_Height = 650;
var ChatWindow_Width = 570;
window.open("Live Chat", "chat", "height=" + ChatWindow_Height + ", width = " + ChatWindow_Width);
//Hidden Form
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://localhost:8080/login");
form.setAttribute("target", "chat");
//Hidden Field
var hiddenField1 = document.createElement("input");
var hiddenField2 = document.createElement("input");
//Login ID
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("id", "login");
hiddenField1.setAttribute("name", "login");
hiddenField1.setAttribute("value", "PreethiJain005");
//Password
hiddenField2.setAttribute("type", "hidden");
hiddenField2.setAttribute("id", "pass");
hiddenField2.setAttribute("name", "pass");
hiddenField2.setAttribute("value", "Pass#word$");
form.appendChild(hiddenField1);
form.appendChild(hiddenField2);
document.body.appendChild(form);
form.submit();
}
To concatenate strings, use the + operator.
To insert data into a URI, encode it for URIs.
Bad:
var url = "http://localhost:8080/login?cid='username'&pwd='password'"
Good:
var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;
The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.
… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).
You can use this but there remains a security issue
<script type="text/javascript">
function fnc1()
{
var a=window.location.href;
username="p";
password=1234;
window.open(a+'?username='+username+'&password='+password,"");
}
</script>
<input type="button" onclick="fnc1()" />
<input type="text" id="atext" />
You can try this instead
var myu = document.getElementById('myu').value;
var myp = document.getElementById('myp').value;
window.opener.location.href='myurl.php?myu='+ myu +'&myp='+ myp;
Note: Do not use this method to pass sensitive information like username, password.
I found this method very useful, I hope this will be helpful for many users too.
// --> screen 1:
var url = 'screen_2_url';
var id = 'some_ID';
window.open(url + '?id=' + id);
This will open the Screen 2 tab. There you can get the passed values like this:
// --> screen 2:
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const id = urlParams.get('id');
I agree that passing username and password as parameters is a bad idea, no matter how you do it.
However, if it's same site, you could use sessionStorage, like so:
sessionStorage.setItem('username', username)
sessionStorage.setItem('password', password)
window.open("http://localhost:8080/login","mywindow")
And then in the opened window:
var username = sessionStorage.getItem('username')
var password = sessionStorage.getItem('password')
// if you no longer need them:
sessionStorage.removeItem('username')
sessionStorage.removeItem('password')