Remove query string on page reload - javascript

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.

Related

Drive Traffic to New Href Link when A Tag is Clicked

I am working to pull the entire URL from the inbound traffic source of a page and extract a single query string value from it, and then use this value as part of a new URL.
The new URL will be used to send traffic to another page when it is clicked.
My code below I checked does go into the fnView function but I can't get the new url to be navigated to when the a tag is clicked.
JavaScript
document.addEventListener('DOMContentLoaded', pEvents);
function pEvents() {
function fnView() {
var queryString = window.location.search;
var utm_content;
if (queryString !== null) {
utm_content = queryString.match(/utm_content=([^&]+)/)[1];
var itemId = utm_content.toString();
snaptr('track', 'VIEW_CONTENT', {
'item_ids': itemId
});
} else {
snaptr('track', 'VIEW_CONTENT');
}
document.getElementById('link').href = "https://www.sitedomain.com/m-pr.cfm?m=91020&u=2346350&p=" + itemId;
};
document.getElementById('link').addEventListener('click', fnView);
};
HTML
<a id="link" href="#">Click me</a>
Try forcing the click after setting the href value. Just add this line:
document.getElementById('link').click();

Javascript - Remove query string from current url

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 :)

Calling an Action Method based on the value of DropDownList and the model

I have a dropdownlist in my View. I need to enable the user to select a value from the dropdownlist and click a button/ActionLink to call another action method in the same controller. The values that needs to be passed to the new ActionMethod are the ID of the selected Value from the dropdownlist and also the ID of the model which is being passed into the View. The model and the Dropdownlist are not linked together by any means.
I have tried onchnage = document.location.href to set the path of the action method and pass a single value to the action method. But the issue with document.location.href is that it appends the url to the existing url which is not appreciated; i.e, the final url turns out be localhost:port/controller1/action1/controller1/action2 which should have been simply localhost:port/controller1/action2
I am looking for a way where it could be done without using javascript as I have already tried it.
Code in the View
#using (Html.BeginForm("Copy","SetValues",FormMethod.Post))
{
<p>
#Html.DropDownList("OptionValueID", null, "Select")
<input type="submit" value="Copy" />
//This is the preferable method though
#*#Html.ActionLink("Copy", "Copy", "SetValues", new { #OptionValueID = #ViewBag.id,#CopyID = CopyDDL.SelectedValue},null)*#
</p>
}
The copy function is going to take two arguments: Id of the selected item and ID that is being passed through ViewBag.id
The View that is being returned by View would a different View
JavaScript that I have tried
<script language="javascript" type="text/javascript">
function copy(_OptionValueID)
{
var url = "/SetValues/Copy";
$.ajax({
url: url,
data: { copyid: _OptionValueID},
type: "POST",
success: function (data) { }
});
response();
}
</script>
It doesn't evaluate at all.
Action Method that calls this View
public ActionResult Index(int id)
{
var ov = db.OptionValue.Include(x => x.Option).FirstOrDefault(x => x.OptionValueID == id);
var opid = ov.OptionID;
var op = db.Option.Include(x => x.TechnicalCharacteristic).FirstOrDefault(x => x.OptionID == opid);
var tcid = op.TechnicalCharacteristicID;
var tc = db.TechnicalCharacteristic.Include(x => x.TcSets).FirstOrDefault(x => x.TechnicalCharacteristicID == tcid);
var tcset = tc.TcSets;
var opv = db.OptionValue.FirstOrDefault(x => x.OptionValueID == id);
ViewBag.OptionValue = opv.OptionVal;
ViewBag.Option = opv.Option.OptionName;
ViewBag.Lsystem = opv.Option.Lsystem.LsystemName;
ViewBag.FamilyName = opv.Option.Lsystem.LsystemFamily.FamilyName;
ViewBag.OptionValID = id;
ViewBag.OptionID = opv.OptionID;
var setValue = db.SetValue.Where(x=>x.OptionValueID==id).OrderBy(x=>x.TcSet.SetName);
ViewBag.OptionValueID = new SelectList(db.OptionValue.Where(x=>x.OptionID==opid), "OptionValueID", "OptionVal");
return View(setValue.ToList());
}
I ahve checked most question relating to this, but none had the overhead of passing two parameters without using a model.
UPDATE: making it more clear
public ActionResult copy(int OptionValueID,int CopyID)
{
//do Something
return View("Error");
}
Above is the Copy Method
OptionValueID = ViewBag.OptionValID //Got from the Action Method Index of SetValues
CopyID = Value from the DropDownlist
Edit Based on Answer
#using (Html.BeginForm("Copy","SetValues",FormMethod.Post))
{
<p>
#Html.DropDownList("CopyID", null, "Select")
<button type="submit" id="Copy" data-id="#ViewBag.OptionValID"> Copy </button>
</p>
}
now the page is being redirected but the no parameters are being passed. Should I be adding routevalues?
You cannot do it without javascript. Your ActionLink() method is parsed on the server before its sent to the client, so any route values are the initial values in the controller, not any edited values the user makes in the view. In order to respond to client side events you need javascript.
You can use ajax to post the values to the server method.
Include a button and handle its click event
<button type="button" id="Copy" data-id="#ViewBag.id">Copy</button>
Script
var url = '#Url.Action("Copy", "SetValues")';
$('#Copy").click(function() {
var optionID = $(this).data('id');
var copyID = $('#OptionValueID').val();
$.get(url, { OptionValueID: optionID, copyID : CopyID }, function(response) {
// do something with the response
});
});
or alternatively if you wanting to redirect, then replace the $.get() with
location.href = url + '?OptionValueID=' + optionID + '&CopyID=' + copyID;
Edit
Based on revised question and comments, if you wanting to post and redirect, there is no need for any javascript or the link. The dropdownlist needs to be #Html.DropDownList("CopyID", null, "Select") so that its selected value is bound to method parameter int CopyID and since the OptionValueID is not edited, then either add its value as a route parameter in the form
#using (Html.BeginForm("Copy", "SetValues", new { OptionValueID = ViewBag.OptionID }, FormMethod.Post))
or add a hidden input for the value
<input type="hidden" name="OptionValueID" value="#ViewBag.OptionID" />

global site variable js

I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.
So lets say i have selected certain items in page A, the list-preview on Page A gets updated.
But if i want to see the list in detail i have to go to page B.
Page A and B bith use the same .js file, the selected items are saved in a array.
How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?
what i thought of was ...
var selectedProductsName = new Array();
in OwnJS.js
the adding items to the preview list works.
i'm only struggling to keep the array unflushed when i go to page B from page A.
HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:
var selectedProductsName = localStorage.getItem("selectedProductsName");
And to set:
localStorage.setItem("selectedProductsName", []);
Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.
You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.)
Save (in Apply.html)
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
.result(function(result) {
profile = result.values[0];
// save all keys to local storage
for (f in profile) localStorage[f] = fields[f];
// more stuff ...
});
to Retrieve (in personal_Info.html)
// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
$("#textfield1").attr(value, firstName);
}
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>

Get the original url in this case with jquery

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

Categories

Resources