OnSuccess of JQ navigate user to another page - javascript

Evening All,
I have a Jquery function running from my aspx page (When a button is clicked).
It runs a [webmethod] which if successful returns to the 'OnSuccess' function.
From here I want to navigate the user to: /Project/Invoices/List.aspx
function Onsuccess(CommentSuccessfullyUpdated) {
if (CommentSuccessfullyUpdated == "TRUE") {
window.location = Invoices/List.aspx //My attempt, but unsuccessful
}
else {
alert("Invoice/Details- Error: Removing Invoice.");
}
}
I think its something to do with window.location but this is as far as I have got.....
Any ideas?

Your List.aspx page URL need to be enclosed in quotes, either " " or ' '.
if (CommentSuccessfullyUpdated == "TRUE") {
window.location = 'Invoices/List.aspx';
}

Related

Want to refresh page one time on particular URL hit

I am trying to refresh the page only one time when a particular URL is hit.
The reason for this is to refresh the data on the view. My URL is
http://localhost:8072/web?#min=1&limit=80&view_type=list&model=pos.order&action=405
And solutions I have tried are
window.onload = function() {
//considering there aren't any hashes in the urls already
if(!window.location.hash) {
//setting window location
window.location = window.location + '#loaded';
//using reload() method to reload web page
window.location.reload();
}
}
(function()
{
if( window.localStorage )
{
//check if reloaded once already
if( !localStorage.getItem('firstLoad') )
{
//if not reloaded once, then set firstload to true
localStorage = true;
//reload the webpage using reload() method
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
$(document).ready(function(){
//Check if the current URL contains '# or hash'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#loaded".
url = document.URL+"#loaded";
location = "#loaded";
//Reload the page using reload() method
location.reload(true);
}
});
None of them worked for me. What is wrong or which direction should I choose?
Your first solution works fine, it just needed a return statement to prevent execution the rest of the code, however if your original url contains a hash, you can do the check like this:
window.onload = function() {
document.getElementById("test").textContent = window.location;
console.log(window.location.hash);
//check for our specific hash argument
if (!window.location.hash.match(/[#&]loaded(&|$)/)) {
alert("the page is about to refresh");
//setting window location
window.location = window.location + (window.location.hash ? "&" : "#") + 'loaded';
//using reload() method to reload web page
window.location.reload();
return;
}
alert("page refreshed");
}
<div id="test"></div>

Problem in reloading page(table) after deleting record from database

I have a ASP.NET CORE MVC application with a table listing some clients (CRUD) and I can delete users when I click in delete.
The problem that i'm trying to resolve is when I refresh the page after delete the records from the listing the listing still show the deleted record when in the database the record is deleted and if I reload (F5) the page manually the record disappear.
I already try the location.reload(), windows.location.reload() and nothing... I can saw that page is reloading but the record don't disappear.
My code is above:
<script type="text/javascript">
function toggleChecked(status) {
$("#checkboxes input").each(function () {
// Set the checked status of each to match the
// checked status of the check all checkbox:
$(this).prop("checked", status);
});
}
function Delete(id) {
var example_table = $("#example1")
var r = confirm("Are you sure you want to Delete?");
if (r == true) {
$.ajax(
{
type: "POST",
url: '#Url.Action("Delete", "Clients")',
data: {
id: id
},
error: function (result) {
alert("error");
},
success: function (result) {
if (result == true) {
example_table.ajax.reload(); // -->> The problem is in this line!
location.reload(); // -->> The problem is in this line!
}
else {
alert("There is a problem, Try Later!");
}
}
});
}
}
$(document).ready(function () {
//Set the default value of the global checkbox to true:
$("#checkall").prop('checked', false);
// Attach the call to toggleChecked to the
// click event of the global checkbox:
$("#checkall").click(function () {
var status = $("#checkall").prop('checked');
toggleChecked(status);
});
});
</script>
The back-end Delete:
[HttpPost]
public bool Delete(int id)
{
try
{
Clients client = db.Clients.Where(s => s.Id == id).First();
db.Clients.Remove(client );
db.SaveChanges();
return true;
}
catch (System.Exception)
{
return false;
}
}
I want that the deleted record disappear in real time without have to refresh the page manually. If you can help me I appreciate.
If the delete is sucessful you could manually remove that item from the list in the sucess of the ajax call.
However with the reload, does the reload of the page call the database and get a list of data? If this is not triggered from the reload then it wont be updating the list. If it is then my only suggestion would be that cookies may be storing the list?
For Server side refresh you can use Response.Redirect(Request.RawUrl)
For Client side refresh you can use window.location.href= window.location
Or document.location.reload() instead of location.reload()

Updating content with onpopstate

I have a hub that loads pages in to a div with the class 'main', and trying to work out how to be able to go back and forth using browser buttons. I have the following on the settings page:
clickHandler(null, null, 'settings');
This calls the following:
function clickHandler(one,two,three) {
history.pushState(one, two, three);
}
I know that up to this part, it is passing the 'settings' variable as the address bar is showing /settings when navigating back. So to try and get settings.php to load in to 'main' I am trying the following:
function updateContent(data) {
if (data == null)
return;
console.log(data);
$(".main").load(data+'.php');
}
window.onpopstate = function(event) {
console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
updateContent(document.location)
};
However, unless I press back twice really quickly, it's not loading the correct page.

why JavaScript form works in Chrome but not in Firefox

i need following function to be execute in Firefox.., but it is working fine in chrome. the problem was when i do 'Inspect Element With Firebug' it is working fine. the method 'EditEncounterBillStatus' is also hitting correctly. but when i don't use 'Inspect Element With Firebug' the method EditEncounterBillStatus is not hitting.. i tried a lot to sort out this. but still i can't can any one help me to find solution thanks in advance.
else if (element.trim() == "Approved") {
var TestPin = prompt("Please Enter your PIN");
if (TestPin != null) {
if (isNaN(TestPin)) {
alert("Please Enter a Valid Pin");
return;
}
else if (TestPin == pin) {
var postVisitData = { VisitId: vid};
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid }, function (data) {
});
window.location = "/Emr/Patients/Show?PID=" + pid;
}
else {
alert("Your Entered PIN Is Incorrect");
}
}
else {
return;
}
}
I would recommend doing it like this
else if (TestPin == pin) {
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid }, function (data) {
window.location = "/Emr/Patients/Show?PID=" + pid;
});
return; // in case of side effects in unseen code
}
i.e. wait until the $.post has finished before changing the window.location
As the rest of your code is unseen there could be side effects of performing this in this way - hence the return where it is - but even then, not knowing the full call stack there could still be side effects - you have been warned
You should change location upon the success of the post call, so put that in your callback function body:
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid },
function (data) {
window.location = "/Emr/Patients/Show?PID=" + pid;
});
This way you are sure you only change location when the post action was executed. Otherwise you risk that you change location before the post happens. In debug mode, and certainly when you step through the code, there is enough time for the post to finish in time, and so your original code then works.

How to use jQuery click event to change href value asynchronously, based on a JSON query

I'm using the bit.ly url shortening service to shorten certain url's being sent to a "share on twitter" function. I'd like to load the bit.ly url only when a user actually presses the share button (due to bit.ly's max 5 parallel reqs limitation). Bit.ly's REST API returns a JSON callback with the shortened url, which makes the whole scenario async.
I've tried the following to stop the click event, and wait for the JSON call to return a value before launching the click.
I have the following simplified code in jQuery(document).ready():
Updated code (oversimplified)!
jQuery("#idofaelement").click(function(event) {
event.preventDefault(); //stop the click action
var link = jQuery(this);
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
}).unbind().click();
});
});
And the following code to handle the bitly shortening (works just fine):
function bitlyJSON(func) {
//
// build apiUrl here
//
jQuery.getJSON(apiUrl, function(data) {
jQuery.each(data, function(i, entry) {
if (i == "errorCode") {
if (entry != "0") {
func(longUrl);}
} else if (i == "results") {
func(entry[longUrl].shortUrl);}
});
});
} (jQuery)
The href gets its value changed, but the final .click() event never gets fired. This works fine when defining a static value for the href, but not when using the async JSON method.
As you outlined yourself:
event.preventDefault(); //stop the click action
That means, BROWSER IS NOT GOING TO THAT URL, if you wish to actually go forward to the long-url location, simply do something like:
document.location.href = longurl;
iirc, jquery doesn't trigger "click" on A elements. I'd try old good "location.href=whatever" in the callback.
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
});
location.href = link.attr("href");
});
I think what you actually want is to return false; from the click event, to prevent the actual following of the href, right?
Like:
jQuery("#idofaelement").click(function(event) {
//event.preventDefault(); //stop the click action
var link = jQuery(this);
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
}).unbind().click();
});
return false;
});
#Tzury Bar Yochay pointed me in the right direction by suggesting I use location.href to update the url. Also #Victor helped with his answer.
I got things kinda working combining the answers, but had issues with the history in firefox. Seems that updating window.location indeed redirected the user, but also removed the "source page" from the history. This did not happen in chrome, safari, ie8, ie8-compatibility or ie7.
Based on this response to another question I was able to create a workaround giving the following working code + made a few changes:
jQuery("#idofaelement").one("click", function(event) {
bitlyJSON(function(shortUrl) {
jQuery("#idofaelement").attr("href", function() {
//process shortUrl
//return finalized url;
});
setTimeout(function() {
window.location = jQuery("#idofaelement").attr("href");
}, 0);
});
return false;
});
Thanks for all the help!

Categories