Rectangle 27 3

Once you refresh the page, you'll still be making server calls for content, even though you've requested them before. PHP headers won't help you out with that.

I think what you need is a client-side caching mechanism of content already requested from the server in the current page.

For this use-case you can use a hash table in JavaScript and query that before you make a call to the server. This will enhance user experience since the user won't have to wait for another request of content he's already seen.

//placeholder for hash table as cache
var cache = [];

var getPage = function(pageNr){
    if(cache[pageNr]){
        //content is already in cache, use it from there
        handleContent(cache[pageNr]);
    }
    else{
        //object with parameteres sent with GET request
        var params = {};
        params.page = pageNr;

        $.ajax({
          url: "getHTML.php",
          data: params,
          cache: false,
          success: function(response){
            //handle your response here
            handleContent(response);

            //store the response in the cache for later use
            cache[pageNr] = response;
          }
        });
    }
};

Now requesting pages will first look in the current cache to see if you have the content. If not, it will make the server call and store the response in the cache.

It is similar to the user-experience when scrolling through news in Google Finance

NOTE that if you refresh the page this cache will be erased.

In case of edits to a page you will have to use Maurice Perry's links to Yahoo Exceptional Performance in order to ensure that your server is always returning your latest version of content.

This will create a pretty big cache[] eventually. This is the reason I was hoping to be able to use PHP Headers to use the build-in browser cache (which probably won't affect performance as much as a huge JS array would.

Unless you are planning to use this as a single application the cache object shouldn't get unreasonably large. When it does, remember it is still stored on the client, in the user's browser. In any case, you can choose to flush it when it reaches a certain point.

I am actually doing a single-page "application". Are you sure it's okay to store objects this big on the client?

If this will be implemented as a single application you might want to have some quota on that hash. Flush it after it reaches a certain size or when the user is unlikely to return to a page.

Depending on the content you store in that hash I'd say it's generally safe to assume that most modern browsers can handle it although I recommend you keep your code tidy and clear that cache from time to time.

php - Cache AJAX requests - Stack Overflow

php javascript jquery ajax caching
Rectangle 27 1

Firstly, PHP will always run before JavaScript - it's server side rather than client side so the cookie you set with JavaScript won't actually be available to PHP until you refresh the page (hence that issue).

Next JavaScript has different ways to encode the strings; only one will work with PHP automatically.

document.cookie = "testuser=" + "Joe|123|my+email@somewhere.com";
// Joe|123|my email@somewhere.com (when decoded by PHP)

document.cookie = "testuser=" + escape("Joe|123|my+email@somewhere.com");
// Joe|123|my email@somewhere.com (when decoded by PHP)

document.cookie = "testuser=" + encodeURI("Joe|123|my+email@somewhere.com");
// Joe|123|my email@somewhere.com (when decoded by PHP)

document.cookie = "testuser=" + encodeURIComponent("Joe|123|my+email@somewhere.com");
// Joe|123|my+email@somewhere.com

So, try this for the sake of a test (remember you'll need to refresh the page to see the cookie value):

<html>
<head>
    <title>Cookie Juggling</title>
    <script type="text/javascript">
        document.cookie = "testuser=" + encodeURIComponent("Joe|123|my+email@somewhere.com");
    </script>
</head>

<body>
    <div><?php echo !empty($_COOKIE['testuser']) ? $_COOKIE['testuser'] : "Cookie not set yet"; ?></div>
</body>
</html>

cookies - Why does PHP replace pluses with spaces in $_COOKIE? - Stack...

php cookies setcookie
Rectangle 27 0

You can remove the iframe node and rebuild it via javascript dynamically.

Below is a basic method in how to do it via jQuery. You'll need a wrapper (<div id="reload"></div>) around your iFrame with an ID called "reload".

$(document).ready(function() {
   setInterval(function() {
      $("#reload").html('<iframe src="/path/to/script.php"></iframe>');
   },5000);
});

This may achieve your goal but is not ideal since it can be a burden on your browser. Ideally async calls to your script and creating HTML nodes by javacript would be the better route. However this will require a little bit more researching/learning on your end in order to build it properly. (you dont get the flashing iframe screen due to reload)

Use javascript or php to force clients to refresh - Stack Overflow

php javascript html
Rectangle 27 0

PHP executes on the server side. JavaScript executes on the client side. Before your page is displayed to the user, PHP has completed its job. You will need to either redirect, refresh, or make an AJAX request, but the point is that you need to send the information back to the server somehow.

getting javascript variables to PHP variables - Stack Overflow

php javascript mysql ajax
Rectangle 27 0

You must combine both javascript and php, as you want to retrieve the information from the database (server side using php+a bit of mysql) with a dynamic page without refresh (client side using javascript). It will certainly become a long difficult job, but I think it's the best approach.

Read this article about double drop down menu and study the code this article (or search for similar projects) and when you understand the javascript, you must fill it where it's appropriate with php.

For example, this is a bit of the javascript (or html) source code:

if (Indx==1)
{
options[0]=new Option("Choose a JavaScript Page","");
options[1]=new Option("Alerts","alerts.htm");
options[2]=new Option("Back and Forward Buttons","BackForward.htm");
options[3]=new Option("Contents","index.html");
}

For your project it should be something like this (not complete and not bug-free, but it's just to give you an idea:

if (Indx==1)
{
<?php
$i=0;
while ($row = mysql_fetch_array($result))
    {
    ?>
    options[<?php echo $i;?>]=new Option("<?php echo $row['name']."\",\"".$row['page']; ?>");

    <?php $i=$i+1; } ?>
}

That should give you the same code (assuming that 'name' and 'page' are values of your columns in your database). And that needs to be done in all convenient javascript bits, but I won't do all your work... give it your best and, if it still doesn't work, come back and ask a more specific question about the code.

If you make it work, I'd like to encourage you to post it here editing your question so everyone can learn from it. Keep in mind that this is how I would approach this problem, but there are surely other ways of doing it.

onChange refresh particular dropdown list in PHP - Stack Overflow

php onchange jcombobox
Rectangle 27 0

You need to educate yourself about server-side vs. client-side operations. Javascript is client side. The server (running PHP in your case) knows nothing about what javascript is doing unless you send some information back. This can be accomplished via a page refresh or via ajax (put simplistically).

What you want is ajax which is an asynchronous request that goes back to the server. The server can then handle it and choose to pass information back to the page. Look into jQuery's ajax.

function com(id) {
    //forget about appending the id. This isn't doing anything.
    //You can use it for informational purposes or so that if someone cuts and pastes
    //the link you can handle it server side appropriately.
    location.href = '#?ID=id';

    //instead focus on this call. append your query string to the url    
    $.ajax({
        type: "POST",
        url: "getdata.php?ID=12345",
        async: true,
        cache: false,
        success: function(data) {
            alert(data); //should alert the id processed by php
        },
    });
}

@AanaSaeed - changing the url without a page refresh does not notify the server of anything. So you need to drop that line of thinking. Instead focus on your ajax call. By calling url: "getdata.php?ID=12345" the receiving page, getdata.php can then parse out the id using $_GET['id'].

Passing the ID to url string via jquery and then picking it by PHP wit...

php jquery url
Rectangle 27 0

Hash tags cannot be read by the server. They are regarded as locations within the document and are therefore not exposed to the server. The client is the only one whom see's these. The best you could do is use a "meta refresh" tag, or alternatively, you could use javascript to detect the url, and if its one which requires 301 redirection, use "window.location" to move the user to a full url where mod_rewrite or a php page can issue a 301 header.

However neither are SEO friendly and only really solve the issue for users that click onto an old link via an external site

<!-- Put in head tag so the page does not wait to load the content-->
<script type="text/javascript">

if(window.location.hash != "") { 

var h = window.location.hash.match(/#\/?(.*)/i)[1];
switch(h) {
    case "something_old":
        window.location = "/something_new.html";
    break;
    case "something_also_old":
        window.location = "/something_also_new.html";       
    break;  
}

}

</script>

Hi Lee, thanks for the advice. At the moment I'd settle for just being able to redirect visitors arriving from old links to be honest. How might I go about implementing your suggestion of using javascript to intercept the incoming requests and redirect as appropriate? I'm not very familiar with Apache yet, so I don't know what I can do with it as yet. Many thanks, Rich.

Hi Rich, is there a common structure, for example all old links are "www.website.com/index#pagename" and they need to redirect to "www.website.com/pagename" or is each old link completely different to one another? Could you provide real samples of from=>to links (replace the domain with website.com if you need anonymity)

Hi Lee, unfortunately the new site is a complete redesign, so there isn't a clean mapping like that. To give an example, on the old site the page might have been www.yorkshiretea.co.uk/#/what_we_care_about, and on the new site this now needs to redirect to www.yorkshiretea.co.uk/about-us/yorkshire-tea-respecting-the-planet.php As you can see, not much correlation between the old URL and the new. There are only a handful of key URLs from the old site that we want to redirect (around 18 or so), so don't mind a bit of manual intervention for each if there is a workaround. Cheers, Rich

Hi Richard, in that case you can either use pure javascript or redirect all hash tags URL's to a php script and process the redirect behind the scenes. I will provide an example of a pure javascript solution above in just a few minutes

.htaccess - Hash character in URLs (accessing and redirecting in Apach...

apache .htaccess url redirect hash
Rectangle 27 0

Since PHP is executed server-side, it doesn't change once the client loads the page. The only way to refresh a div without JavaScript is to reload the page.

I would try using AJAX to get the name from the other file and update the HTML with JavaScript

jquery - Refresh Div Containing PHP Function - Stack Overflow

php jquery refresh
Rectangle 27 0

The reason why you can't live edit PHP is because it is a server-side script, not a client side script like JavaScript. Thus, you will not see live updates in Chrome; you will need to refresh to get updates.

PHPStorm does support debugging PHP, though, just in a different way: JetBrains PHP Debug Documentation

Yes,but i could see the for example echo 'hi' in browser? Could u please give me a tutorial on how to set everything up?

So it is not possible to do PHP debuggin in browser? Even with local php server?

No, because the browser does not process PHP! The server does. In that documentation I sent you, you can see the result in the browser, however; you cannot do any sort of manipulation of the PHP from the browser, rather this is done in PHPStorm.

Yes, i just want to see the result in the browser :D

browser - PHPStorm open index.php in Chrome using live edit? - Stack O...

browser live edit phpstorm
Rectangle 27 0

If I understand you correctly, you're trying to use a PHP to code to refresh the webpage? However, the issue here is that once the PHP is output to the client, you can't have control over it already. The best thing to do in this context is to use JavaScript to do the refresh for you. Hope it helps :)

Hi Merlin, you might want to use a simpler logic like this:

<script type="text/javascript">

    var reloaded = false;
    var loc=""+document.location;

    loc = loc.indexOf("?reloaded=");

    if (loc == -1){
      window.location.replace(window.location+"?reloaded=true");      
    }
</script>

Optionally you might want to pack it into a function for your use. Hope it helps (:

Now I have used a code to refresh the page. But it is not showing the changed image all the time.

and I would like to add a code to refresh div without refreshing the whole page

For your point on refreshing the div without the whole page, the best is to use a JavaScript with either a setInterval() or setTimeout() function. As for your first point on the refresh not showing, have you checked that it has not been cached in your browser?

No the page is not cached.

javascript - How to refresh a div in which php code is executing - St...

php javascript ajax refresh page-refresh
Rectangle 27 0

What a refresh technically does is force the client to manually ask for new data - even if none exists. What you're trying to do is, however, to have your server/backend push new changes as they become available.

There are a number of methods to perform this. Here's a good place to start: Simple "Long Polling" example code?

Use javascript or php to force clients to refresh - Stack Overflow

php javascript html
Rectangle 27 0

PHP will always send you a new page because it is a server side language. In order for this code to be executed when a user clicks the button and then the results shown to the user, the request must be sent to the server, executed, and then sent back to the user. The only way you can 'refresh' a page like you are requesting is to use a client side language such as javascript.

It is like this: When user clicks the submit button they are requesting that PHP process the request. This can only take place on the server. Because the request goes from user to server and then back to user, you will always get a new page.

php - How To Make 'Submit' Button Refresh Page? - Stack Overflow

php html echo contact-form
Rectangle 27 0

Firstly, PHP will always run before JavaScript - it's server side rather than client side so the cookie you set with JavaScript won't actually be available to PHP until you refresh the page (hence that issue).

Next JavaScript has different ways to encode the strings; only one will work with PHP automatically.

document.cookie = "testuser=" + "Joe|123|my+email@somewhere.com";
// Joe|123|my email@somewhere.com (when decoded by PHP)

document.cookie = "testuser=" + escape("Joe|123|my+email@somewhere.com");
// Joe|123|my email@somewhere.com (when decoded by PHP)

document.cookie = "testuser=" + encodeURI("Joe|123|my+email@somewhere.com");
// Joe|123|my email@somewhere.com (when decoded by PHP)

document.cookie = "testuser=" + encodeURIComponent("Joe|123|my+email@somewhere.com");
// Joe|123|my+email@somewhere.com

So, try this for the sake of a test (remember you'll need to refresh the page to see the cookie value):

<html>
<head>
    <title>Cookie Juggling</title>
    <script type="text/javascript">
        document.cookie = "testuser=" + encodeURIComponent("Joe|123|my+email@somewhere.com");
    </script>
</head>

<body>
    <div><?php echo !empty($_COOKIE['testuser']) ? $_COOKIE['testuser'] : "Cookie not set yet"; ?></div>
</body>
</html>

cookies - Why does PHP replace pluses with spaces in $_COOKIE? - Stack...

php cookies setcookie
Rectangle 27 0

I had the same problem as you. I'm building a site that sounds a lot like yours, also using PHP to enable and disable page elements before and after the broadcast time. Your solution seemed promising, but ultimately I was dissatisfied using pure Javascript for the page reload. Javascript gets its time from the client's machine, whereas PHP gets it from the server, and even a small difference between the two could wreck the whole system. (i.e. the page could refresh 30 seconds before the PHP enabled the buttons, causing some viewers to assume the whole thing is down.)

I solved the problem by using PHP to tell the Javascript function what time it is, and it works like a charm. The only issue is that it runs every day, instead of just on one day of the week, but that doesn't bother me- users will have no reason to be viewing the page other than the broadcast day.

This is all you need- I put this right after the <body> tag:

<script type="text/javascript">
setTimeout(function() { window.location.reload(true); }, 1000*<?php 
$then = mktime(15,00,0);
$tomorrow = mktime(15, 00, 0, date("m") , date("d")+1);
$now = time(); 
if ($now > $then) {echo $tomorrow - $now;}
else {echo $then - $now;}?>); </script>

javascript - How to refresh page on specific day at specific time in s...

javascript date timezone refresh
Rectangle 27 0

If i understand your question correctly, You want to validate the users input without a page reload or refresh, Doing this without client side scripts is as far as i know Impossible. Once PHP (Pre Hypertext Processor) has finished playing with your code its then sent to the client and PHP "Goes to sleep" until another page is loaded. Javascript is the best way to achieve your desired result. This isnt really an answer i guess but what your trying to do is act upon data that has not been sent to the server using only a server side technology. It is not possible.

Javascript can be a pain in the rear but there are tools out there now that make debuging simple Chrome even has a dev console built in that takes sme of the pain out of it.

php - Smooth login without javascript - Stack Overflow

php html login
Rectangle 27 0

I've seen the server.php from the link you've provided, and it simply:

You need to alter this loop and add another source for messages, and you have 2 options. You can pool a DB or open another TCP socket and read from there.

However, the best solution is to use NodeJS with Socket.io and DNode (very elegant solution that works cross-browser and is not that difficult), but you need to be able to install NodeJS on your server. I can provide samples if you want.

I'll assume you are familiar with Debian based distributions (I'm going to install things with APT). First I'll explain some things:

  • NodeJS is a server-side javascript interpreter that will run our socket part. In fact, we will use both PHP and NodeJS (the latter only for updating clients, so your existing code will not change much)
  • NPM is a command line utility (that comes with NodeJS). Its main purpose is for installing packages (Socket.io and DNode are NPM packages)
  • Socket.io is a wrapper around WebSockets that make it works cross-browser. It also contains the server-side handling functions
  • DNode is an RPC for communicating with other languages/servers (in this case, with our PHP script)

First we install NodeJS. The version on Ubuntu repo's is veeery old, so we add a PPA from here:

sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install node
cd
server.js
//import libraries
var io = require('socket.io');
var dnode = require('dnode');

var clients = []; //this array will hold all connected clients

var srv = io.listen(8080, { log: false }); //this port must be different from apache
srv.sockets.on('connection', function(socket){
    console.log("Client connected.");
    clients.push(socket);

    //this will be called when a javascript client sends us something. you can delete this if you don't need it
    socket.on('message', function(data){
        console.log(data); 
    });

    socket.on('disconnect', function(){
        console.log("Lost client.");
        var i = clients.indexOf(socket);
        clients.splice(i, 1); //remove from array
    });
});

var dnode_server = dnode({
    //expose a "send" function
    send: function(data, cb){
        for(i = 0; i < clients.length; i++){
            clients[i].emit('update', { //send an "update" message to all connected clients
                title: data.title, //some data
                text: data.text
            });
        }
        cb(null, false); //inform PHP that the processing is done. You can also return something
    }
    //you can have multiple functions here
});
dnode_server.listen(5004); //this port should not be accessible from the ouside
npm install socket.io
npm install dnode

You can run this script using node server.js

Now we need to edit the clientside javascript. Import Socket.io using this:

<script type="text/javascript" src="http://YOURHOSTNAME:SOCKETIOPORT/socket.io/socket.io.js"></script>
socket = io.connect('http://YOURHOSTNAME:SOCKETIOPORT');
socket.on('connect', function(data){
    alert('Connected!');
});
socket.on('disconnect', function(){
    alert('Disconnected :( are you offline?');
});
socket.on('update', function(data){ //our function call
    alert(data.title + " " + data.text);
});

You can send data to server like on NodeJS:

socket.emit('message', {foo: 'bar'});

Finally, you want to trigger "update" on all connected clients from a PHP script. For this, we need a PHP library for interfacing DNode. You can find it here and its usage is very simple:

$dnode = new \DnodeSyncClient\Dnode();
$connection = $dnode->connect('localhost', 5004);
$connection->call('send', array(array(
    'title' => "My awesome title",
    'text' => "My awesome text"
)));

Thank you JohnKiller for this information! I never used NodeJS before. I would not bother you, but if you have time for samples, why not :). Thank you again!

no problem, just let me know if you got any issues :)

Websockets PHP / AJAX / Javascript refresh client - Stack Overflow

javascript php jquery ajax
Rectangle 27 0

Well, PHP is a server-side language, and Javascript is client side, which means, you can't pass variables to php without a post. You can use an AJAX post, if you don't want to refresh the page. On the other hand, it is fairly easy to use PHP variables in jQuery, so if that is reasonable for your work, you should consider that.

How can I use jQuery variable inside PHP tag - Stack Overflow

php jquery
Rectangle 27 0

Jarrod is correct, the IP alone is not sufficient. I would also like to point out that JavaScript alone will not be enough to do this either. The best thing I could come up with would be to have PHP return a list of all of authenticated and active users based off the session. You could then set up a script on the client side to poll the back-end script you write and just refresh some section of the page with the list provided. For specifics regarding PHP user sessions please see: Looping Through All a Server's Sessions in PHP

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Is there a way to detect users are on the same page? - St...

javascript ajax
Rectangle 27 0

The database lives on your web server. The javascript is running on the client computer. If you want to store the co-ordinates in the database on the server, you are going to have to post the data to the web server and let the web server take care of updating the database. There are many ways to get the coordinates to the web server. One is to use XHR (XML HTTP Request) which will not do a page refresh. Another way is to update window.location.href with a URL that contains the name of the php program that will update the database and the x and y values. This will do a page refresh. There are many other ways as well. The main thing to remember is that the php code runs on one computer, the javascript runs on another. You can not intermingle js code with php code, but...... You can use php to write js code for you (very few people do, but it works) just like we routinely use php code to write HTML code. I think that may be a source of your confusion. It looks like one computer is running both languages, but it is not. The server runs the php which may create js to send to the browser running on the client but it is not executing the js code, just "writing" it so that it can be executed by the client when it gets there.

Having a PHP code block within a JavaScript code - Stack Overflow

javascript php jquery html
Rectangle 27 0

PHP is a server side language. You cannot use php on client side. If you want to do something on client side, use JavaScript. If you want to use php with your html either you have to refresh the page(see answer of Patrik Evans), or use Ajax. If you are planning to use ajax as it is fast and simple, move your php to a different file like index-form.php and call it by ajax get method.

Basically when you load the page via browser, browser first lookup for your site IP from DNS. Then your server will compile the whole page (ignoring html, js and other client side script) and compile the server side scripts like PHP, Perl, Python etc depending upon the type of server. Then your server will send the compiled page to your browser and browser will read it, compile the client side scripts and render it in your viewport.

Using HTML variable in PHP in .php from Select - Stack Overflow

php html variables null html-select