A callback for a page refresh function - javascript

Is there any way to implement a callback for a page refresh function, check if the page is ready after it is refreshed and then print a message? I'd like to show refresh the page and show a certain message after clicking a button, however, I need to stay within my code in order to know what message to show. Anything similar to the next code would be great:
location.reload(function(){
alert ('done refreshing and document is ready');
});

On page reload, your JS application gets re-initialized and starts all over again, so you cannot have a callback.
However, what you can do is add a hash fragment to the URL before reloading.
window.location = window.location.href + "#refresh";
window.location.reload();
Then, on page load, check if the hash fragment exists. If it does, you'll know you just refreshed the page.

If you want to user window.location.reload() you have to use Browser's sessionStorage. Here is my code, I use this for saving data.
window.onload = function () {
var msg = sessionStorage.getItem("nameShah");
if (msg == "Success") {
sessionStorage.setItem("nameShah", "");
alert("Saved Successfully");
}
}
$("#save").click(function () {
$.ajax({
url: "/AspNetUsers/SaveData",
type: "POST",
async: true,
data:{userName: "a"},
success: function (data) {
if (data.Msg == "Success") {
sessionStorage.setItem("nameShah", "Success");
window.location.reload();
}
}
});
});
Server Side:
public ActionResult SaveData(string userName)
{
return Json(new { Msg = "Success" }, JsonRequestBehavior.AllowGet);
}

The way to go is using
$(document).ready(function(){
alert('done refreshing and document is ready');
});
But it doesn't differentiate a first load from a refresh. But you could achive that using sessions. For example, using PHP:
<?php
session_start();
$showJs = false;
if( !isset($_SESSION['loaded_before']) ) {
$showJs = true;
$_SESSION['loaded_before'] = true;
}
?>
...
<?php if($showjs) { ?>
<script type="text/javascript">
$(document).ready(function(){
alert('done refreshing and document is ready');
});
</script>
<?php } ?>

If you really want to go javascript side, you can use sessionStorage.varName before reloading, and then you check that var and continue.

Related

AJAX function to detect when session is expired and log out

I have this function that checks if a session in the current tab has expired. However, if I open another tab and log out through there, my current tab won't know and somehow it maintains its session until I access an item from the navigation menu. Is there a way I can improve this by detecting when a user has either logged out or if the users session has expired?
The main issue right now is if they open another tab and just log out from there.
function check_if_logged_in(){
$.ajax({
method: "POST",
url: "<?php echo site_url('Common/CheckSession'); ?>",
beforeSend: function () {
$('.loading').show();
},
success: function(data){
if(data==="undefined"||data===null||data===0){
console.log("logged out");
// window.location.replace("<?php // echo BASE_URL;?>");
}else{
console.log("logged in");
}
$('.loading').fadeOut("slow");
},
});
}
This is my checkSession function
public function checkSession(){
if($this->logged_in()===false){
echo false;
}else{
echo true;
}
}
this->logged_in() just checks if the session is still active.
I have read about LocalStorage by HTML5. I'm wondering if this will affect mobile devices as the site itself is responsive and I've heard that iOS or some devices don't support LocalStorage.
You should write a js function which can be accessed in every file. Most probably in your footer.
Then write the below code which will be called at an interval of every 5 seconds(You can change it according to your convinience).
$( document ).ready(function() {
setInterval(function () {
checkSession();
}, 5000);
});
function checkSession()
{
$.ajax({
type: "POST",
url: "your_session_checking_function",
success: function (data) {
data = JSON.parse(data);
if(data.response != "true")
{
window.location.href = 'redirect to login page';
}
}
});
}
Then according to the result obtained in ajax success you can redirect it to the login page.

Jquery refresh the page after success

How do I refresh the page after ajax call success. The page doesn't refresh even thought I have put window.location.reload(true). It only displays the echo message but doesn't refresh it
$("#update-btn").click(function() {
var token = document.getElementById('tokenAmount').value;; //Place the token here
var master = currentUserID;
var lastUser = lastNode.info.id;
$.ajax({
type : "POST",
url : "update.php",
data : {'master': master,
'token' : token,
'user_id': lastUser
},
success : function(data) {
alert(data);
window.location.reload(true);
}
});
});
update.php
$master=$_POST['master'];
$user = $_POST['user_id'];
$token = $_POST['token'];
if(condition)
{
$result = $MySQLi_CON->query($secondToken);
if($result == false)
$response['msg'] = "Not Enough";
else
{
$response['msg'] = "Successful";
}
}
else
{
$response['msg'] = "Not enough";
}
echo json_encode($response['msg']);
Please try below code :-
location.reload();
Edited :-
success : function(data) {
alert(data);
location.reload();
}
Other ways :-
location.reload()
history.go(0)
location.href = location.href
location.href = location.pathname
location.replace(location.pathname)
location.reload(false)
Please have a look on below link :- There are 534 other ways to reload the page with JavaScript :-
http://www.phpied.com/files/location-location/location-location.html
.ajaxStop() callback executes when all AJAX call completed. This is a best place to put your handler.
$(document).ajaxStop(function(){
window.location.reload();
});
The source is from here
The next statement wont execute unless you click Ok on alert().
So use console.log(data) instead.
success : function(data) {
console.log(data);
window.location.href=window.location.href;
}
Try this:
location.reload(true);
In your ajax success callback do this:
success: function(response){
setTimeout(function(){
location.reload()
}, 5000);
}
As you want to reload the page after 5 seconds, then you need to have
a timeout as suggested in the answer.

Ajax page return nothing on refresh the page button click

I made an ajax function calling php pages from a /pages folder and i call my pages in a ajax-container div, but when i click on the refresh the page button the history pushstate is working because i see the page in the adress, but it's loading only the content of my index.php but nothing happens in my ajax-container.
So how can i get the page i called when i refresh the page?
htacces:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^([a-zA-Z0-9\-]*).php$ index.php?p=$1 [L]
ajax-container:
<div id="ajax-container">
<?php
$d = "pages/";
if (isset($_GET['p'])) {
$p = strtolower($_GET['p']);
if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".php")) {
include $d . $p . ".php";
} else {
include $d . "404.html";
}
} else {
include $d . "home.php";
}
?>
</div>
and my ajax function:
var afficher = function(data, page) {
$('#ajax-container').delay(200).fadeOut(250, function() {
$('#ajax-container').empty();
$('#ajax-container').append(data);
$('#ajax-container').fadeIn(100, function() {});
});
};
var lastRequest = null;
if (lastRequest !== null) {
lastRequest.abort();
}
var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}
lastRequest = $.ajax({
url: "pages/" + page,
cache: false,
success: function(html) {
afficher(html, page);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
return false;
};
window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.php');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});
I see, well I don't understand jquery since I've only worked with pure javascript AJAX. However, I do know some things to check.
1-Is your php echoing things out? Even if you get a php file by AJAX, it won't display anything unless the information is being echoed out.
2-I don't see a innerHTML, as with my experience (again only used pure javascript AJAX), the echoed php code would be put in the div's innerHTML. Example with your div:
before ajax:
<div id="ajax-container">
hello
</div>
AJAX gets php file:
AJAX finishes and the content is ready... ( xmlhttp=XMLHttpRequest() )
document.getElementById("ajax-container").innerHTML=xmlhttp.responseText;//responseText= whatever php echoed out
after AJAX:
<div id="ajax-container">
hi
</div>
This replaces the div's content, the following would add to it:
document.getElementById("ajax-container").innerHTML.=xmlhttp.responseText;
note the period for concat^
3- if you still having problems, open up your browser developer tools->network tab->php file name
This will allow you to see whatever the php file is saying (var_dumps, echos, errors if error reporting stuff allows it)

Is it possible to load content of page without Refreshing the whole page

Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );

Help submitting a form to a JQuery script using a javascript submit() function

I attempted to ask this question last week without a resolution. I am still unable to get this to work. What I would like to do is submit data entered through a WYSIWYG javascript editor to a JQuery script I have that will first tell the user if they are trying to submit an empty textbox The last thing I need it to do is tell the user if their data was entered successfully or not.
I am having a problem inside the JQuery script as nothing is being executed when I click the save button.
This editor uses javascript submit() that is tied to a small save icon on the editor. When the user presses the button on the editor, it fires the function I have in the form tag. That's about as far as I was able to get.
I think there is an issue with the form tag attributes because when I click anywhere on the editor, the editor jumps down off the bottom of the screen. I believe it has something to do with the onclick event I have in the form tag.
The first part of the JQuery script is supposed to handle form validation for the textarea. If that's going to be really difficult to get working, I'd be willing to let it go and just handle everything server side but I just need to get the data POSTed to the JQuery script so that I can send it to my php script.
Thanks for the help guys.
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
function doSave()
{
$(function()
{
$('.error').hide();
$(".rpt").click(function()
{
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "")
{
textArea.show();
textArea.focus();
return false;
}
else
{
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
return false;
});
});
}
There are a few things you need to change. Firstly this:
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
isn't the jQuery way. Plus its not the click() event you want. Do this:
<form name="rpt" class="rpt" id="rpt" action="">
<script type="text/javascript">
$(function() {
$("#rpt").submit(do_save);
});
</script>
The construction:
$(function() {
..
});
means "when the document is ready, execute this code". It is shorthand for and exactly equivalent to the slightly longer:
$(document).ready(function() {
..
});
This code:
$("#rpt").submit(doSave);
means "find the element with id 'rpt' and attach an event handler to it such that when the 'submit' event is executed on it, call the do_save() function".
And change doSave() to:
function doSave() {
$('.error').hide();
$(".rpt").click(function() {
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "") {
textArea.show();
textArea.focus();
return false;
} else {
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if (data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
});
return false;
}
Note: return false is in the correct place now so it actually prevents the form submitting back to the server. action="" just means the form will submit back to its current location so you have to prevent that.
function X() {
$(function() {
//... things you want to do at startup
});
};
Doesn't do what you want. Nothing is ever executed, because you never tell it to be executed.
You might want to try something like:
<script type="text/javascript">
jQuery(function($) {
//... things you want to do at startup
});
</script>
Also, you want the onsubmit event of the form. You can use
$('#theform').submit(function() {
//... perform the ajax save
});
In addition, you may want to look into the Form plugin.

Categories