public JsonResult UnassToOrder(string location, string article_number)
{
//....
return Json(new {
success = true,
redirect = "ImportXML/Index"
});
}
<script type="text/javascript">
$(document).ready(function() {
$('input:radio').click(function() {
var location = $("input:checked").val();
var article_number = $("input[id=MArticleNumber]").val();
$.post("/SomeController/SomeAction", { location: location, article_number: article_number }, function(data) {
window.location.href = data.redirect;
},"json");
});
});
</script>
I have 3 radio buttons. When click on first one I have redirect to "ImportXML/Index" with this line of code: window.location.href = data.redirect;. When I click on second radio button my URL on browser is "ImportXML/ImportXML/Index" and this is error because correct URL is "ImportXML/Index"
You can absolutize your path like this:
window.location.href = "/" + data.redirect;
I would highly recommend using the UrlHelper class to build your URLs.
return Json(new {
success = true,
redirect = Url.Action( "Index", "ImportXML ")
});
Related
I am kinda new to asp.net mvc website with jquery, razor, javascript and html. Right now my actionlink has a problem where I cannot insert the filter part, into ..page/?sortMethod=StartDate
filters?=pending generates from a button (pending is just 1 of the many status)
?sortMethod=StartDate generates from actionlink.
I am trying to make them work together to get:
..page/?filters?=pending&sortMethod=StartDate
I tried to do a script that tries to replace the
This is the initial code, sortMethod is a string.
<script>
$(function () {
$("#filterUidClear").click(function () {
$("#filterUid").val('');
});
$('#filterPending').checkboxradio();
$('#filterDirect').checkboxradio();
$('#ApplyFilter').click(function () {
var params = "";
if ($('#filterPending')[0].checked) {
params = "filters=pending";
}
if ($('#filterDirect')[0].checked) {
if (params !== "") {
params = params + "&";
}
params = params + "filters=direct";
}
$("#param").val("?" + params);
window.location.href = "?" + params;
});
});
</script>
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate })
This is the new modified one
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate }, new { id = action })
<script>
$(function() {
$('#action').click(function() {
var filterparam = $("#param").val();
this.href = this.href + '?filters=' + encodeURIComponent(filterparam) + '&sortMethod=' + #ViewBag.StartDate;
});
</script>
I am trying to make them work together to get:
..page/?filters=pending&sortMethod=StartDate but to no avail.
The table will display filtered with pending results and sorted by date
Right now it displays ..page/?action&sortingMethod=StartDate
the table shows sorted by date but no filter and action is not being replaced by filter type e.g. ?filters=pending
public ActionResult GiveTicket(Guid voteId, Guid applyId,string cptcha)
{
//檢查此票選是否允許此登入方式
var canVoteWay = _voteService.GetVoteWay(voteId);
string message = string.Empty;
string loginPath = $"{ConfigurationManager.AppSettings["DomainName"]}/Account/Login?returnUrl={Request.UrlReferrer}";
//檢查是否已登入
if (User.Identity.IsAuthenticated && WebLogic.HasValue(canVoteWay, (int)CurrentUser.LoginType))
{
// [驗證圖形驗證碼]
if (string.IsNullOrEmpty(cptcha) || cptcha != Session["VerificationCode"]?.ToString())
{
Response.Write("<script language=javascript> bootbox.alert('圖形驗證碼驗證錯誤,請重新輸入!!')</script>");
return null;
}
//var result = _voteService.GiveTicket(voteId, applyId, CurrentUser.Id, CurrentUser.LoginType);
Response.Write("<script language=javascript> bootbox.alert('投票成功')</script>");
return null;
}
message = _voteService.VoteWayString(canVoteWay, "請先登入,才能參與投票!! 投票允許登入的方式:");
Response.Write("<script language=javascript> if (confirm('" + message + "',callback:function(){})){window.location = '" + loginPath + "'}</script>");
return null;
}
My ajax code
function GiveTicket(applyId) {
var voteId = $('input[name="Id"]').val();
var captcha = $('input[name="Captcha"]').val();
$.ajax({
url: '#Url.Action("GiveTicket", "Vote")',
data: { applyId: applyId, voteId: voteId, cptcha: captcha },
type: 'Get',
success: function (data) {
console.log(data);
//bootbox.alert(data);
}
});
}
Like you see. I have many condition. SomeTime I need to pass alert or confirm to
web client . when I pass confirm. if user click Yes. I need to redirect Url.
So that I decide to write string to web client.
The problem is How I can just execute string from MVC like alert,confirm...
hello hopefully this post help you
you can passe your string to view using viewbag or viewModel as you like then in this view you put your redirect logic using razor.
I'm trying to use HtmlUnit to get data fom a web site,
so far i managed to enter the data needed in order to login (username & password).
The problem begins with the fact that the website login form dosent have a submit button, instead there is an href that has an onClick JavaScript function (onclick="login_submit())
that verify data and then call window.location = "index.php";
So i tried clicking the href using:
HtmlAnchor anchor = page.getAnchorByText("כניסה");
page = anchor.click();
and tried:
page.executeJavaScript(javaScriptCode);
but the page variable dosent get the expected page, it got the same url as before clicking and there is no redirection. Once the login_submit() function is called there is a label that indicates " login.." but nothing happens from there.
Here is the code:
// javascript login_submit() -- this is not my website and not my JS code so ive deleted some things:
function login_submit()
{
if(!LOGIN_SUBMIT_PROCESSED)
{
var approved = true;
var admin_user_username_field = document.getElementById('admin_user_username');
var admin_user_username_error = document.getElementById('admin_user_username_error');
var admin_user_password_field = document.getElementById('admin_user_password');
var admin_user_password_error = document.getElementById('admin_user_password_error');
admin_user_username_field.className = "login_form_field_input_text";
admin_user_username_error.style.display = 'none';
admin_user_password_field.className = "login_form_field_input_text";
admin_user_password_error.style.display = 'none';
if(admin_user_username_field.value.length == 0)
{
//do something
}
if(admin_user_password_field.value.length == 0)
{
//do something
}
if(approved)
{
LOGIN_SUBMIT_PROCESSED = true;
document.getElementById("login_form_options").style.display = "none";
document.getElementById("login_form_process").style.display = "";
var http_request = new XHConn();
http_request.connect(
"login_submit.php?cache="+string_unique(),
"POST",
"form_anti_bot_code="+encodeURIComponent(form_anti_bot_code_field.value)
+ "&admin_user_username="+encodeURIComponent(admin_user_username_field.value)
+ "&admin_user_password="+encodeURIComponent(admin_user_password_field.value),
function(response,callback_data)
{
if(response.readyState == 4)
{
if(response.status == 200)
{
//alert(response.responseText);
try
{
var json_response = JSON.parse(response.responseText);
if(json_response["error_code"] == "0")
{
window.location = "index.php";
}
else
{
//do something
}
}
catch(error)
{
alert(error);
}
}
LOGIN_SUBMIT_PROCESSED = false;
}
},
null
);
}
}
}
Java code:
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setCssEnabled(true);
//webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setRedirectEnabled(true);
HtmlPage page = (HtmlPage) webClient
.getPage(url);
HtmlForm form = page.getFormByName("login_form");
form.getInputByName("admin_user_username").setValueAttribute("XXXXX");
HtmlInput passWordInput = form.getInputByName("admin_user_password");
passWordInput.removeAttribute("disabled");
passWordInput.setValueAttribute("XXXXXX");
HtmlAnchor anchor = page.getAnchorByText("Login");
page = anchor.click();
System.out.println(page.getBody().asText());
webClient.close();
}
I know for a fact after some testing that the login data is ok, href is clicked and there is an indicator that login is being proccesed.
the main problem is that its not redirecting and dont get the "index.php" page.
Try this and it should do the trick:
WebWindow window = page.getEnclosingWindow();
This might do the trick:
final HtmlPage page2 = page.getElementById("Login_Button").click();
I need only one tab accessible for my website. When he tries to open in new tab or even tries to copy and paste the url in new tab should clear the user's session and logout from the application.
There are several reasons,
When a user opens a new tab connecting to the same application - the session id is the same.
Imagine that this user has reached a page X in the application flow from the first tab.
When he opens the second tab he might be in one of the following scenarios - depending how the second tab was opened - new tab, duplicate tab (this copies the URL to the newly opened tab), or new session.
All of the above will "confuse" the server as to what the next valid state of the application is, and could override data entered in different tab, without his/her knowledge
What I want is to prevent a single user to have several tabs in the same session, i.e. only one tab/window per user, per session.
Including the below script in dashboard.php after login
<script>
$(document).ready(function()
{
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
else
{
sessionStorage.pagecount = 1;
}
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
});
Below code in other sub pages in the application
<script>
$(document).ready(function()
{
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
});
</script>
Added the below script after I login(say dashboard.php)
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
Added the below script in Header in rest of my pages - 'random_value' is from db for that user
<script>
$(document).ready(function()
{
$("a").attr("target", "_self");
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
if('<?=$random_value?>' == window.name)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
Hello there
I am developing a jQuery plugin that loads files through ajax. When user clicks on a button which is:
<button class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
When user clicks on button it generates following url:
http://localhost//plugins/ajaxLoad/index.html#ajax/Login
I want to change it to
http://localhost//plugins/ajaxLoad/index.html/ajax/Login
My javascript is:
(function ($) {
$.fn.ajaxLoad = function (options) {
var settings = $.extend({
fileUrl : 'null',
loadOn : '.em'
}, options);
$('[data-load="ajax"]').each(function(index, el) {
$(this).click(function () {
var file = $(this).attr('data-file');
var loadOn = $(this).attr('data-load-on');
var permission = $(this).attr("data-ask-permission");
settings.fileUrl = file;
settings.loadOn = loadOn;
if (permission == 'yes') {
var ask = confirm("Do you want to load file");
if (ask == true) {
$.fn.loadFile();
}
}else {
$.fn.loadFile();
}
});
});
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.split(".");
location.hash = a[0];
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
}(jQuery))
Can anyone tell me how to change url in jquery and Javascript.
You need to use history.pushstate() to do this.
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Have a look at this article on MDN for more details
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
This article gives some nice jQuery examples.
https://rosspenman.com/pushstate-jquery
Added another attribute title to button
<button data-title="login" class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
In Js (after $(this).click line):
var title = $(this).attr('data-title');
settings.title = title
Just replace
location.hash = a[0];
With
history.pushState('','',"?"+settings.title);
Change
location.hash = a[0];
to:
location.pathname += '/' + a[0];
Just replace the hash with a blank using .replace()
Example .
settings.fileUrl.replace('.' , ' ');
Updated above also
UPDATE :
Don't hash the URL
Example :
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.replace("." , "/");
location.href = a;
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}