0

I'm currently using below method to call an external php file with some variables using javascript

<script src="http://www.domain.com/function.php?param=A" type="text/javascript"></script>

And the code in the function.php file will return data in Javascript format, something like

<?php Header("content-type: application/x-javascript");
$p = $_GET['param'];

$r = mt_rand(0, 10);
echo "document.write('" . $p . $r . "');";
?>

This is just a simple example. My problem is on Google Chrome (v19), if the page had not finished loaded, the random number will not be random when I keep refreshing. It will become truly random only when I hit the refresh button AFTER the page finished load. Why is this happen and how can I solve it?

I tested on Firefox 12 and IE8, even if I refresh the page before it finished load, the random number will always be regenerated.

3
  • Is there a reason you're not using Javascript's Math.random()? Commented May 29, 2012 at 4:41
  • Sorry maybe I make the example here too simple. I actually was loading MySQL database in the PHP file, load some data and randomly select one of them to pass back to the page which is calling it. Commented May 29, 2012 at 4:43
  • Try adding some no-cache headers to the response. Commented May 29, 2012 at 4:46

2 Answers 2

0

You need a small JS hack. Basically, you want to dynamically add the <script> tag in JS and add a random parameter at the end of the URL.

var hookScripts = function(url, src) {
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = url || null;
    s.innerHTML = src || null;
    document.getElementsByTagName("head")[0].appendChild(s);
};

hookScripts('http://www.domain.com/function.php?param=A&randomSalt=' + Math.random());  

This will force chrome to request the JS file again.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! The random salt method solved my problem! Anyway I combined php code into the Javascript src to generate the random salt (because I need to insert that section of Javascript code at multiple parts of webpage).
0

Your URL's query string says param=A, you're referencing $_GET['param1'] on your PHP/JS file. Shouldn't it be $_GET['param']?

You'll probably want to add the headers so that your js file is not cached

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

See http://php.net/manual/en/function.header.php

1 Comment

Thanks. I added the header, but the problem still persists. And only in Google Chrome...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.