How do I reload a page without the user noticing? - javascript

I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?

Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});

Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:

You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!

Related

Auto Refresh PHP Function without reloading page Javascript / Ajax

Is it possible to use Ajax, Jquery or Javascript to call a specific PHP Function and refresh / reload it every 10 seconds for example inside a specific Div or areas?
Connection.php
function TerminalStatus ($IPAddress, $portStatus ) // Responsible for current terminal status
{
$connectStatus = fsockopen($IPAddress, $portStatus, $errno, $errstr, 10); // Build cconnection to Terminal socket 25001
if (!$connectStatus) {
echo "$errstr ($errno)<br />\n";
} else {
$Status = fgets($connectStatus) ;
echo $Status ();
}
}
This connection is just to see the current status of a terminal.
I want to see the status of this function at the bottom of my index.php without refreshing the whole page.
I can accomplish this by putting this function in its own PHP Files (status.php) and using Javascript in the following way:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#Status').load('status.php');
}, 1000); // refresh every 1000 milliseconds
</script>
But i just want to utilise the function instead.
Is this possible?
The solution you have already is the correct way to do this: the JavaScript fetches a URL, and that URL renders the appropriate piece of content.
It's important to remember that, as far as the web browser is concerned, PHP doesn't exist. Any request from the browser - whether you've typed in a URL, followed a link, submitted a form, made an AJAX request, etc - is just a message to some remote server for a particular URL, perhaps along with some extra headers and body data. When the server receives that request, it can do whatever it likes to generate a response to the browser.
So when you write $('#Status').load('status.php');, the browser is sending a request to the server, which happens to be configured to execute the PHP script status.php. You can then do what you like in PHP to produce the response - but there is no direct link between a request and a PHP function.
However, as others have pointed out, you don't have to create a new PHP file for every piece of behaviour you want, because inside the PHP code you can check things like:
the query string parameters, in $_GET
submitted form data, in $_POST
the HTTP headers from the request
These can be set by your JavaScript code to whatever you like, so you could for instance write $('#Status').load('index.php?view=statusonly'); and then at the top of index.php have code like this:
if ( $_GET['view'] === 'statusonly'] ) {
echo get_status();
exit;
}
How you arrange this is entirely up to you, and that's what programming is all about 🙂
That's impossible to do this operation just with the PHP function.
you should use javascript as you use that or use socket in javascript to connect you status.php and update without refresh the whole page.
I'm not sure if i understood the problem but you can use AJAX to execute specific function. Something like this:
First build your ajax:
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus", // this will call the function
success: function(status){
$('#Status').text(status); // this will load the info you echo
},
});
Since you want to do it every second - wrap the whole thing with interval (i use your code from the question):
var auto_refresh = setInterval( function () {
$.ajax({
type: "POST",
url: "URL_TO_PHP_FILE",
data: "refreshStatus",
success: function(status){
$('#Status').text(status);
},
});
}, 1000);
Then, on you PHP_FILE add condition the execute the specific function when POST been done:
if ($_SERVER["REQUEST_METHOD"] == "POST" && $_POST['refreshStatus']) {
// run this code
}
Is that what you aimed to achieve?
jQuery::load() supports fragment identifiers. So you can just load the part that you want to replace:
$( "#Status" ).load( "status.php #PartId" );
This will load the HTML output of the script and extract the part. The PHP script will run completely - the rest of the HTML output will be thrown away on the JS side.

window.location.reload(true) not reloading the page correctly

I have a PHP page which fetches data from a MYSQL database and generates HTML content based on rows returned from the database.
I am adding a new row in database on click of a button using AJAX, Jquery and PHP. After adding the new row, I am using window.location.reload(true); to reload the page. But the HTML elements corresponding to new row are not shown when I click the button. However, if I manually refresh the page using F5, the newly added content is shown.
Anyone knows why this could happen?
Below is the function which I call on click of a button. The page increaseCount.php updates database to increase the count of actors. But the HTML elements corresponding to new count are not shown until I refresh the page using F5.
function increaseCountOfNewActor(characterName) {
var actorName = document.getElementById("txt_actor_"+characterName).value;
var actorImage = document.getElementById("img_actor_"+characterName).src;
$.ajax( {
url: "increaseCount.php",
method: "POST",
data: {
name: actorName,
image: actorImage,
character: characterName
},
success: function( data ) {
alert("Vote received");
}
} );
window.location.reload(true);
}
The problem is that you are mixing ajax with a complete page reload.
The $.ajax call by default is asynchronous (the first a from ajax...). Therefore it sends a request to increasepostcount.php and then immediatelly reloads the page - not waiting for increasepostcount.php to process the request. By the time you manually refresh the page, increasepostcount.php will have completed the processing of the ajax call, therefore its result are reflected on the page.
If you use ajax, you should not use page reloading. Use javascript to update that part of the page where these records are displayed based on the results returned by the ajax call.
You need to be sure that the ajax call has done to do what you want, in your case "window.location.reload(true);" is running before the ajax response, due to asynchronous communication between Client and Server to avoid "freezing" on the screen and an unresponsive user experience.
You have to put your refresh code on Success ajax response or on done :
function increaseCountOfNewActor(characterName) {
var actorName = document.getElementById("txt_actor_"+characterName).value;
var actorImage = document.getElementById("img_actor_"+characterName).src;
$.ajax( {
url: "increaseCount.php",
method: "POST",
data: {
name: actorName,
image: actorImage,
character: characterName
},
success: function( data ) {
alert("Vote received");
// to do here
//window.location.reload(true);
}
} ).done(function () {
// or to do here
window.location.reload(true);
});
}
in your page increaseCount.php consider adding a header at the end.
For example:
if(isset($_POST['name'] &&
isset($_POST["image"] &&
isset($_POST["character"]) {
/* do your stuff here */
header("Location: /thePageYouWantToRefresh.php");
exit;
}

How to store/remember the data fetched from ajax call?

I'm retrieving some data into a JSON array, then display it into an HTML table which contains some data enclosed within hyper links. i.e. a couple of the columns' data are clickable, once clicked it displays another JSP page (say page #2) with some more data which was kept on the JSON array itself.
Now this page 2 has a 'Back' button functionality - the expected behavior is when user clicks the 'Back' button it should go back to page 1 where the HTML table data was displayed and user should be able to see the data which they first fetched too. i.e. there should be some way to remember the data fetched from my initial AJAX request and retrieve the same data which user fetched in page 1 when they go back to that page from the child page#2.
Th AJAX call is triggered when user enters an account# and the type of account - I fetch data accordingly and get the result in the 'response' object and neatly display it on html table, but after user moves from that page and again hits the back button I see the page#1 without the table. Now again I cannot ask the user to re-enter the details to see the data that they retrieved earlier. It's pretty annoying.
Please give me a solution to this problem. Thanks All.
Appreciate for taking time to read this.
Here's a part of the code:
$(document).ready(function () {
var flag = "1";
$('#accountType').bind('change', function (event) {
var accountType = $('#accountTypeSelect').val();
var account = $('#accountText').val();
jQuery.ajax({
type: 'POST',
url: '${pageContext.request.contextPath}' + "/Page1.spr", //request page
cache: false,
dataType: "json",
data: {
"accountType": accountType,
"account": account,
"flag": flag
}, //data sent to request page
success: function (response) {
// code to display the data into the html table
},
error: (function (message) {
console.log("error message : " + message);
}),
statusCode: {
404: function () {
alert("page not found");
}
}
});
});
You can save the data in HTML5 sessionStorage or localStorage using the setItem method as follows:
success: function(response) {
sessionStorage.setItem("result", response)
// code to display the data into the html table
}
And access it later using the getItem() When you come back to the page like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// code to be executed when old dats is found
}
else{
}
Ideally you code in first pages load will be something like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// data exists : code to be executed when old dats is found
}
else{
jQuery.ajax({}) // send the AJAX request to fetch data
}
You can read more about session and local Storage here
Browser support for web storage API.
Update
If you don't have HTML5 support, you could use jQuery cookie plugin (There are plenty of others as well) for storing data at client side.
You can store data into a cookie as follows:
$.cookie("result", response);
Then to get it from the cookie like:
$.cookie("result");
You maybe can use cookie via jquery. But user have to enable the browser's cookie. It usually enabled by default setting.
To add:
$.cookie("key1", data1);
$.cookie("key2", data2);
To read:
$.cookie("key1");
To delete:
$.removeCookie("key1");
So, you can try to read cookie to load table data, if no data, call ajax:)
Another way is to save it in a hidden input:
success: function(response){
$("#hiddenInput").val(JSON.stringify(response));
}

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

how to send asynchronous request to php page using jquery ajax

i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?
data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>
The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.
If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.

Categories

Resources