简体   繁体   中英

Set JavaScript file to a variable in PHP

Okay so I'm trying to set a JavaScript document to a variable in PHP?

Essentially I'm setting the WiFi speed I calculate in a Javascript document to a variable,so I can save the variable value in a database with other information as an instance.

The Javascript code is pretty long so I don't know if I should copy the whole code in and set it equal to the variable or if there's a syntax to set it to a variable.

I've seen:

<script type="text/javascript" src="file.js"></script>

Online for calling a Javascript file but not sure how to get that value and store it in a variable.

You could do something like this

$js = file_get_contents( 'http://www.example.com/javacsript.js');

$value = trim( str_replace( array( "document.write('", "');"), '', $js));

echo $value;

Hope this will help you

The JavaScript must be executed in the browser client. The flow would be:

  1. PHP generates HTML (wich includes the JS code)
  2. HTML is sent to the browser
  3. The browser renders the HTML and executes the JS
  4. The browser communicates with the server to tell the result

Depending if the JS is a library or an script the precise steps would differ. But basically inside tags you will have to save the result to a variable and then make an AJAX call (easier with jQuery.ajax() ) to communicate that variable to the server and then the server can do something with it.

I hope that helps puting you on the right track. If you expand the info in your question, I will try to update my answer :)

You have to do this using a POST, possibly to the same PHP script.

<form method='post' id=myform>
 <input type=hidden id=js-to-php value=0>
</form>
<script>
jQuery(document).ready(function(){
 //calulcate the wifispeed using the long js code
 //then save it in the field
 $('#js-to-php').val(YOUR_SPEED);
 // send the form
 $('#myform').submit();
});
</script>

and then in the same script:

if( isset($_POST['js-to-wifi']) && $_POST['js-to-wifi']!='') {
  // store your stuff in DB
}

So here is the Java script code:

//Source: http://stackoverflow.com/questions/5529718/how-to-detect-internet-speed-in-javascript


var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg"; 
var downloadSize = 4995374; //bytes

window.onload = function() {
    var oProgress = document.getElementById("progress");
    oProgress.innerHTML = "Loading the image, please wait...";
    window.setTimeout(MeasureConnectionSpeed, 1);
};

function MeasureConnectionSpeed() {
    var oProgress = document.getElementById("progress");
    var startTime, endTime;
    var download = new Image();
    download.onload = function () {
        endTime = (new Date()).getTime();
        showResults();
    }

    download.onerror = function (err, msg) {
        oProgress.innerHTML = "Invalid image, or error downloading";
    }

    startTime = (new Date()).getTime();
    var cacheBuster = "?nnn=" + startTime;
    download.src = imageAddr + cacheBuster;

    function showResults() {
        var duration = (endTime - startTime) / 1000;
        var bitsLoaded = downloadSize * 8;
        var speedBps = (bitsLoaded / duration).toFixed(2);
        var speedKbps = (speedBps / 1024).toFixed(2);
        var speedMbps = (speedKbps / 1024).toFixed(2);
        oProgress.innerHTML = "Your connection speed is: <br />" + 
           speedBps + " bps<br />"   + 
           speedKbps + " kbps<br />" + 
           speedMbps + " Mbps<br />";
    }
}

I want to get the value that this will return (I will edit the code so I am only getting one value) and then place it inside a php variable. The issue is when I run it on a webpage after using:

$Speed = file_get_contents( 'wiFiCalc.js');
$value = trim( str_replace( array( "document.write('", "');"), '', $Speed));
echo $value;

I just get the code on the html page, as clami219 stated above. I just want to return that value to print it and store it in the database.

Also, Jobst, the way you wrote was kind of hard to follow. I am using a form action in my html code to go to the speed so it can be stored in the database before it returns to the next HTML page so could you explain how your code works?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM