location.reload after ajax post - javascript

I have a $.ajax() call that does some server-side updates. After it's finished (in the "success" function), I call location.reload(true) to refresh the page. I do want the "true" there because I do want the new changes to appear, as opposed to getting the cached version of the page that doesn't have them. This all works nicely in FF (27.0.1). However, it is NOT working in IE 10. And, it is not working in Chrome (33.0.1750.149). (I'm working in asp.net MVC, in case that matters.)
In fact, the entire ajax call is not made (ie: the updates don't even happen on the server). When I comment out the line, the ajax call works perfectly, but obviously no reload.
I tried all the following options in IE 10. Some reload the page, just the cached version. Some break the entire ajax call.
window.location.reload(true); --> breaks ajax call
window.location.reload(); --> breaks ajax call
window.location.href = window.location.href --> works, but cached version is reloaded
Any other ideas? I'm even open to doing a full ajax/jquery redirect to the page?
Here's the ajax function:
function ExecuteFlagAssign() {
.....//some code here...not important....//
$.ajax({
type: 'POST',
url: '/Services/poAJAX.asmx/SetPOInfo',
data: "{inPOCombinedIDList: \'" + masterItemIDList + "\', inParameters: \'" + JSON.stringify(paramObj) + "\'}",
dataType: "json",
contentType: "application/json; charset=utf-8;",
success: UpdateCompleteFlagAssign(callFrom),
error: UpdateErrorFlagAssign
});
}
function UpdateCompleteFlagAssign(callFrom) {
if (callFrom == "po_detail" || callFrom == "so_detail" || callFrom == "so_detail_top") {
window.location.reload(true);
}
}
Just to add one more point (don't think it's important, but who knows): the button that calls the javascript is on a popup. However, it's not a real modal popup. It's actually just a hidden div that gets a high z-index (so it appears) when it's requested.
This javascript code is all on the main page (not the partial view that has the popup display).
So, when I comment out the window.location.reload(true) line, it all works, ajax call fires, updates are made, etc. Just no reload. When I DON'T comment out the line, page DOES reload, but ajax call is not fired/updates don't occur. (no error in developers tools in IE)
Any ideas? I'm really baffled. I'm open to work-arounds here.....
(I know one work-around is to make this a full postback to the server, instead of an ajax call that then refreshes the page. But, that's a decent amount of work. And, there are some pages that call this function that DON'T require a refresh...so it's kinda nice to just use the same ajax call in all cases.)
I really appreciate anyone's time & help on this!!!

Related

JQuery append() information remains even after hard refresh

I made an Ajax call using JQuery and appended (using div.append()) the returned information to a div. This Ajax call was called when clicking on another div on the page. But even after a hard refresh in multiple browsers, the appended information from the previous call stays there, furthermore some of the links in the div it was appended to don't work. I also tried clearing the cache on both the browsers and the server but it didn't work(and found out that they don't store cache on the server).
If it means anything at all, here is the code I used, which I have since commented out:
$("#LogoutDiv").click(function() {
$.ajax({
url: 'header.php',
type: 'POST',
data: {
NumLgtRqt: 1
},
success: function(response) {
$("#HeaderContainer").append(response);
window.location.replace("index.php");
}
});
}
Thank you very much for your help!
The problem was that I put script tags in the append () function. Even though they were inside the append output and in quotations, they still registered to the html.

page will not refresh after a jQuery post

I have a button call this script, so it does the post in the background, but I need to reload the current page to display an updated php query, I realize there was probably a better way in jquery to the query part, but its crunch time, and all I want to do is get a successful page refresh.
Because the buttons were generated in php, the javascript code is at the end of the body.
I've tried location.href, window.location.reload(true);, document.write which only wrote to the page, document.location.href did nothing.
We are using jQuery/jQuery mobile, I was not on front end dev team, so I'm desperate to get this to work. to clarify, I need a page refresh after the $.post() command, within this code, which does work
<script type="text/javascript">
$('#reserveBook').click(function () {
var isbn = sessionStorage.getItem('isbn');
$.post(
"../inventory/postpage.php",
{ isbn: isbn }
);
});
</script>
There's no point in using AJAX if you need a page refresh regardless. As Dan Bracuk said in his comment, you'd be better off just doing a traditional form submission.
However, if you're set on having the page refresh, just add window.location.reload() in the success handler for your AJAX call:
$.post(
"../inventory/postpage.php",
{ isbn: isbn },
function(response) {
window.location.reload();
}
);

Load an Internal file into a div via link without refreshing the page

I'm trying to when a link is clicked on the side of the page grab a another page from my site thats in the same directory and show it into a div called content.
::Optionally:: if i could figure out an easy way to do it without a refresh otherwise refresh the page.
link is
Service Call
my jquery was...not sure if it would work
$("#servicecall").click(function() {
$("#content").load("servicecall.php");
});
Content is my div on the right side where the servicecall.php form would be.
All that seems to happen is my page does a refresh and nothing shows up in content.
When you click the button it gives back an error or something? For example here: http://jsfiddle.net/9839Q/4/
When i click the Service Call link it gives me an error with the following line (Chrome):
GET http://fiddle.jshell.net/_display/index.php 404 (NOT FOUND)
Be sure you added the jQuery Library to your page ! Maybe you just forgot it
<script src="http: //ajax.googleapis.com/ajax/libs/jquery/1.8/jquery. min .js"></script> //without spaces
If none of them, you can try $.ajax (hope it works :)) :
$.ajax({
url: "servicecall.php",
type: "GET",
cache: false,
success: function (html) {
//place servicecall.php's content to the content div
$('#content').html(html);
}
});

AJAX response has script tags in wrong location

I have an issue on a website where a page content (results) are updated via AJAX. Contained within this AJAX returned content is a script tag which renders the LinkedIN "share" button.
When the page first loads with the initial resultset the layout looks like this:
Each of these buttons is within a left-floated div, and the HTML looks like this in Chrome developer tools:
As you can see the script tag is appearing where it is supposed to be, in the div, and the dynamically generated span containing the button is just above.
Now, when i append more results via an AJAX request, things go a bit haywire, and look like this:
As you can see the LinkedIN button is way out of place, and the reason is apparent when looking at the HTML in developer tools:
The script tag is not within the div where it appears in the code file, instead appearing after the closing tr tag - and the span with the button is just above.
So, why is this, and more importantly what can be done to ensure that the script tag is where it belongs so that the layout is correct?
FYI - At the foot of the body is javascript which loads the LinkedIn .js file and after the AJAX request for more results completes there is an invocation of the LinkedIn .parse() method which is supposed to parse the full document and render the buttons.
EDIT
The application is built using ASP.NET MVC and the response returned uses the same .ascx control to format the results as the initial page load does.
EDIT - AJAX request used to retrieve extra data
function LoadMore(uri, last, loader, end)
{
isLoading = true;
$(loader).show();
$.post(uri, function(data)
{
if (data != "")
{
$(last).after(data);
isLoading = false;
// re-do social media share initialisation on the new AJAX-added content
gapi.plusone.go('container');
twttr.widgets.load();
FB.XFBML.parse();
IN.parse(document.body);
}
else
{
$(end).show();;
}
$(loader).hide();
});
}
EDIT
The actual HTML returned from the server is correct. Viewing the source shows the script tag in the correct location, but viewing the page in Chrome developer tools, as shown in the images above, shows the script in the wrong place in the DOM. This occurs in both IE9 and Chrome.
Are you building the html dynamically ? Maybe it has something to do with misconfigured callbacks. If you are using $.ajax({...}), make sure that the next iteration is specified into the "success:" property to prevent unordered render.
Use ajax call like this
$.ajax({ url: 'url',
type: 'POST',
data: json,
dataType: 'json',
contentType: 'text/html',
success: function (data) {
//you response will be data
}
});

How do I refresh a page using JavaScript?

How do I refresh a page using JavaScript?
Use location.reload().
For example, to reload whenever an element with id="something" is clicked:
$('#something').click(function() {
location.reload();
});
The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache. The parameter defaults to false, so by default the page may reload from the browser's cache.
There are multiple unlimited ways to refresh a page with JavaScript:
location.reload()
history.go(0)
location.href = location.href
location.href = location.pathname
location.replace(location.pathname)
location.reload(false)
If we needed to pull the document from
the web-server again (such as where the document contents
change dynamically) we would pass the argument as true.
You can continue the list being creative:
window.location = window.location
window.self.window.self.window.window.location = window.location
...and other 534 ways
var methods = [
"location.reload()",
"history.go(0)",
"location.href = location.href",
"location.href = location.pathname",
"location.replace(location.pathname)",
"location.reload(false)"
];
var $body = $("body");
for (var i = 0; i < methods.length; ++i) {
(function(cMethod) {
$body.append($("<button>", {
text: cMethod
}).on("click", function() {
eval(cMethod); // don't blame me for using eval
}));
})(methods[i]);
}
button {
background: #2ecc71;
border: 0;
color: white;
font-weight: bold;
font-family: "Monaco", monospace;
padding: 10px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.5s ease;
margin: 2px;
}
button:hover {
background: #27ae60;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This works on all browsers:
location.reload();
Lots of ways will work, I suppose:
window.location.reload();
history.go(0);
window.location.href=window.location.href;
To reload a page with jQuery, do:
$.ajax({
url: "",
context: document.body,
success: function(s,x){
$(this).html(s);
}
});
The approach here that I used was Ajax jQuery. I tested it on Chrome 13. Then I put the code in the handler that will trigger the reload. The URL is "", which means this page.
Edit2: The original question was "How to reload a page with JQUERY"! Downvoters take note.
Edit: Unfortunately, I'll have to take down this answer very soon because, the question has changed and the user seemed to not be very clear on what they were asking. Some users have commented that refreshing is different from reloading a page; See the revisions to this question [https://stackoverflow.com/posts/5404839/revisions] As far as I can tell, from the original question which was around refreshing a page with AJAX which is ASYNCHRONOUS ..., refreshing a page should imply getting new and updated content to the page. Anyway, this answer will soon go away./
If the current page was loaded by a POST request, you may want to use
window.location = window.location.pathname;
instead of
window.location.reload();
because window.location.reload() will prompt for confirmation if called on a page that was loaded by a POST request.
The question should be,
How to refresh a page with JavaScript
window.location.href = window.location.href; //This is a possibility
window.location.reload(); //Another possiblity
history.go(0); //And another
You're spoiled for choice.
You may want to use
location.reload(forceGet)
forceGet is a boolean and optional.
The default is false which reloads the page from the cache.
Set this parameter to true if you want to force the browser to get the page from the server to get rid of the cache as well.
Or just
location.reload()
if you want quick and easy with caching.
Three approaches with different cache-related behaviours:
location.reload(true)
In browsers that implement the forcedReload parameter of location.reload(), reloads by fetching a fresh copy of the page and all of its resources (scripts, stylesheets, images, etc.). Will not serve any resources from the cache - gets fresh copies from the server without sending any if-modified-since or if-none-match headers in the request.
Equivalent to the user doing a "hard reload" in browsers where that's possible.
Note that passing true to location.reload() is supported in Firefox (see MDN) and Internet Explorer (see MSDN) but is not supported universally and is not part of the W3 HTML 5 spec, nor the W3 draft HTML 5.1 spec, nor the WHATWG HTML Living Standard.
In unsupporting browsers, like Google Chrome, location.reload(true) behaves the same as location.reload().
location.reload() or location.reload(false)
Reloads the page, fetching a fresh, non-cached copy of the page HTML itself, and performing RFC 7234 revalidation requests for any resources (like scripts) that the browser has cached, even if they are fresh are RFC 7234 permits the browser to serve them without revalidation.
Exactly how the browser should utilise its cache when performing a location.reload() call isn't specified or documented as far as I can tell; I determined the behaviour above by experimentation.
This is equivalent to the user simply pressing the "refresh" button in their browser.
location = location (or infinitely many other possible techniques that involve assigning to location or to its properties)
Only works if the page's URL doesn't contain a fragid/hashbang!
Reloads the page without refetching or revalidating any fresh resources from the cache. If the page's HTML itself is fresh, this will reload the page without performing any HTTP requests at all.
This is equivalent (from a caching perspective) to the user opening the page in a new tab.
However, if the page's URL contains a hash, this will have no effect.
Again, the caching behaviour here is unspecified as far as I know; I determined it by testing.
So, in summary, you want to use:
location = location for maximum use of the cache, as long as the page doesn't have a hash in its URL, in which case this won't work
location.reload(true) to fetch new copies of all resources without revalidating (although it's not universally supported and will behave no differently to location.reload() in some browsers, like Chrome)
location.reload() to faithfully reproduce the effect of the user clicking the 'refresh' button.
window.location.reload() will reload from the server and will load all your data, scripts, images, etc. again.
So if you just want to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic. But it will not reload the page if there is a hash (#) in the URL.
The jQuery Load function can also perform a page refresh:
$('body').load('views/file.html', function () {
$(this).fadeIn(5000);
});
As the question is generic, let's try to sum up possible solutions for the answer:
Simple plain JavaScript Solution:
The easiest way is a one line solution placed in an appropriate way:
location.reload();
What many people are missing here, because they hope to get some "points" is that the reload() function itself offers a Boolean as a parameter (details: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload).
The Location.reload() method reloads the resource from the current
URL. Its optional unique parameter is a Boolean, which, when it is
true, causes the page to always be reloaded from the server. If it is
false or not specified, the browser may reload the page from its
cache.
This means there are two ways:
Solution1: Force reloading the current page from the server
location.reload(true);
Solution2: Reloading from cache or server (based on browser and your config)
location.reload(false);
location.reload();
And if you want to combine it with jQuery an listening to an event, I would recommend using the ".on()" method instead of ".click" or other event wrappers, e.g. a more proper solution would be:
$('#reloadIt').on('eventXyZ', function() {
location.reload(true);
});
Here is a solution that asynchronously reloads a page using jQuery. It avoids the flicker caused by window.location = window.location. This example shows a page that reloads continuously, as in a dashboard. It is battle-tested and is running on an information display TV in Times Square.
<!DOCTYPE html>
<html lang="en">
<head>
...
<meta http-equiv="refresh" content="300">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script>
function refresh() {
$.ajax({
url: "",
dataType: "text",
success: function(html) {
$('#fu').replaceWith($.parseHTML(html));
setTimeout(refresh,2000);
}
});
}
refresh();
</script>
</head>
<body>
<div id="fu">
...
</div>
</body>
</html>
Notes:
Using $.ajax directly like $.get('',function(data){$(document.body).html(data)}) causes css/js files to get cache-busted, even if you use cache: true, that's why we use parseHTML
parseHTML will NOT find a body tag so your whole body needs to go in an extra div, I hope this nugget of knowledge helps you one day, you can guess how we chose the id for that div
Use http-equiv="refresh" just in case something goes wrong with javascript/server hiccup, then the page will STILL reload without you getting a phone call
This approach probably leaks memory somehow, the http-equiv refresh fixes that
I found
window.location.href = "";
or
window.location.href = null;
also makes a page refresh.
This makes it very much easier to reload the page removing any hash.
This is very nice when I am using AngularJS in the iOS simulator, so that I don't have to rerun the app.
You can use JavaScript location.reload() method.
This method accepts a boolean parameter. true or false. If the parameter is true; the page always reloaded from the server. If it is false; which is the default or with empty parameter browser reload the page from it's cache.
With true parameter
<button type="button" onclick="location.reload(true);">Reload page</button>
With default/ false parameter
<button type="button" onclick="location.reload();">Reload page</button>
Using jquery
<button id="Reloadpage">Reload page</button>
<script type="text/javascript">
$('#Reloadpage').click(function() {
location.reload();
});
</script>
You don't need anything from jQuery, to reload a page using pure JavaScript, just use reload function on location property like this:
window.location.reload();
By default, this will reload the page using the browser cache (if exists)...
If you'd like to do force reload the page, just pass a true value to reload method like below...
window.location.reload(true);
Also if you are already in window scope, you can get rid of window and do:
location.reload();
use
location.reload();
or
window.location.reload();
<i id="refresh" class="fa fa-refresh" aria-hidden="true"></i>
<script>
$(document).on('click','#refresh',function(){
location.reload(true);
});
</script>
This works for me.
function reload(){
location.reload(true);
}
Use onclick="return location.reload();" within the button tag.
<button id="refersh-page" name="refersh-page" type="button" onclick="return location.reload();">Refesh Page</button>
If you are using jQuery and want to refresh, then try adding your jQuery in a javascript function:
I wanted to hide an iframe from a page when clicking oh an h3, for me it worked but I wasn't able to click the item that allowed me to view the iframe to begin with unless I refreshed the browser manually...not ideal.
I tried the following:
var hide = () => {
$("#frame").hide();//jQuery
location.reload(true);//javascript
};
Mixing plain Jane javascript with your jQuery should work.
// code where hide (where location.reload was used)function was integrated, below
iFrameInsert = () => {
var file = `Fe1FVoW0Nt4`;
$("#frame").html(`<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${file}\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe><h3>Close Player</h3>`);
$("h3").enter code hereclick(hide);
}
// View Player
$("#id-to-be-clicked").click(iFrameInsert);
All the answers here are good. Since the question specifies about reloading the page with jquery, I just thought adding something more for future readers.
jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML.
~ Wikipedia ~
So you'll understand that the foundation of jquery, or jquery is based on javascript. So going with pure javascript is way better when it comes to simple things.
But if you need a jquery solution, here's one.
$(location).attr('href', '');
There are many ways to reload the current pages, but somehow using those approaches you can see page updated but not with few cache values will be there, so overcome that issue or if you wish to make hard requests then use the below code.
location.reload(true);
//Here, it will make a hard request or reload the current page and clear the cache as well.
location.reload(false); OR location.reload();
//It can be reload the page with cache
You can write it in two ways. 1st is the standard way of reloading the page also called as simple refresh
location.reload(); //simple refresh
And another is called the hard refresh. Here you pass the boolean expression and set it to true. This will reload the page destroying the older cache and displaying the contents from scratch.
location.reload(true);//hard refresh
you may need to use
location.reload()
or also may need to use
location.reload(forceGet)
forceGet is a boolean and optional.
Set this parameter to true if you want to force the browser to take the page from the server to receive rid of the cache as well
Simple Javascript Solution:
location = location;
<button onClick="location = location;">Reload</button>
Probably shortest (12 chars) - use history
history.go()
$(document).on("click", "#refresh_btn", function(event)
{
window.location.replace(window.location.href);
});
It is shortest in JavaScript.
window.location = '';
Y'all may need to use
location.reload(forceGet)
forceGet is a boolean and optional.
The default is false, which reloads the page of the cache.

Categories