将javascript值传递给html

将javascript值传递给html

问题描述:

This is related to my previous question: retrieving video from database using php

On the previous question i pass the speedMbps in javascript using a ajax form and $( "#speed" ).val( html ); expect a return value so i am unable to embed my html code in viewvideo.php.

I thought of a different way to pass the speedMbps into my php.

Passing the value speedMbps into my html form which can used the method POST to sent the data to my php file.

var imageAddr = "testimage.jpg"; 
var downloadSize = 2097152; //bytes

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

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

    download.onerror = function (err, msg) {
        oProgress.value = "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);
        return speedMbps;
        oProgress.value = "Your connection speed is:        <br />" + 
           speedBps + " bps<br />"   + 
           speedKbps + " kbps<br />" + 
           speedMbps + " Mbps<br />";

document.getElementById("speed").value = speedMbps;   

Html code

                <input type="text" id="speed" name="speed" value="">

viewvideo.php

$speed= $_POST['speed'];

Edited: when i echo $speed in my php file it does not get echo.. look like no value is pass from the javascript to my html form.

error on console is unexpected end of input on

document.getElementById("speed").value = speedMbps;

i solve the problem.

deleting return speedMbps; i manage to retrieve the value and pass the value into my php file.

Your are using return statement before setting up data into form.

document.getElementById("speed").value = speedMbps;    return speedMbps;