www.webdeveloper.com
Results 1 to 15 of 15

Thread: [RESOLVED] uncaught ReferenceError and I am confused

  1. #1
    Join Date
    Mar 2014
    Location
    Corpus Christi, TX
    Posts
    88

    resolved [RESOLVED] uncaught ReferenceError and I am confused

    All,

    Again as a newbie to Javascript, I am trying to automate a speed test that will send the results of the test to a php script. I have fumbled around with this, and believe I am making progress. Below is my script which is giving me the error: "Uncaught ReferenceError: testResult is not defined" on line 70. Line 70 reads: "var the_data = 'onTestCompleted='+testResult.download;" Please remember that I am new to this. I would appreciate steps to help me learn how to fix this, and why this isn't working to begin with.

    Full code below:

    Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript">
    	
    	// create the XMLHttpRequest object, according browser
    	var xmlHttp = new XMLHttpRequest();
    function get_XmlHttp() {
      // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
      var xmlHttp = null;
    
      if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
        xmlHttp = new XMLHttpRequest();
      }
      else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
    
      return xmlHttp;
    }
    
        </script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    
    
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		SomApi.startTest();
    		 
    	}
    	
    	function onTestCompleted(testResult) {
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    	
    
    
    
    // sends data to a php file, via POST, and displays the received answer
    function ajaxrequest(php_file, tagID) {
     
      // create pairs index=value with data that must be sent to server
      var  the_data = 'onTestCompleted='+testResult.download;
    
      request.open("POST", php_file, true);			// set the request
    
      // adds  a header to tell the PHP script to recognize the data as is sent via POST
      request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      request.send(the_data);		// calls the send() method with datas as parameter
    
      // Check request status
      // If the response is received completely, will be transferred to the HTML tag with tagID
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          document.getElementById(tagID).innerHTML = request.responseText;
        }
      }
    }
    
    (function(){ setTimeout(btnStartClick, 1500); })();
    (function(){ setTimeout(ajaxrequest, 100000); })();
    </script>
    </body>
    </html>

  2. #2
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    872
    The error means exactly what is says: testResult is not defined.

    The line in question is inside of the function ajaxrequest(). Inside of this function there is absolutely no variable named testResult. The variable testResult in your code is a private variable that is only declared inside of the function onTestCompleted() as an argument/parameter. This means that outside of that function, the variable simply doesn't exist.

    From what I can tell, it looks like you are trying to run a second ajax request after the test runs which will send the test result to some other script. Rather than set it to run after a delay (of 100 seconds) you should just have it trigger after the test is complete. It would look something like this:
    Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript">
    	
    	// create the XMLHttpRequest object, according browser
    	var xmlHttp = new XMLHttpRequest();
    	function get_XmlHttp() {
    		// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    		var xmlHttp = null;
    		if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
    			xmlHttp = new XMLHttpRequest();
    		}	else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return xmlHttp;
    	}
    </script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		SomApi.startTest();
    		 
    	}
    	
    	function onTestCompleted(testResult) {
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    		ajaxrequest(?, ?, testResult);
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    
    	// sends data to a php file, via POST, and displays the received answer
    	function ajaxrequest(php_file, tagID, testResult) { 
    		// create pairs index=value with data that must be sent to server
    		var  the_data = 'onTestCompleted='+testResult.download;
    
    		request.open("POST", php_file, true);			// set the request
    
    		// adds  a header to tell the PHP script to recognize the data as is sent via POST
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.send(the_data);		// calls the send() method with datas as parameter
    
    		// Check request status
    		// If the response is received completely, will be transferred to the HTML tag with tagID
    		request.onreadystatechange = function() {
    			if (request.readyState == 4) document.getElementById(tagID).innerHTML = request.responseText;
    		}
    	}
    
    	(function(){ setTimeout(btnStartClick, 1500); })();
    </script>
    </body>
    </html>
    The real change was that I added a new argument, parameter to your ajaxrequest() function called 'testResult'. Then I added a line at the end of the onTestCompleted() function that will run the ajaxrequest() function (and pass the testResult variable). However I should note I have two question marks in there as you never specified the php_file or tagID, which will be required in that function. You will need to enter the correct data in place of those question marks if you want the code to work.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  3. #3
    Join Date
    Mar 2014
    Location
    Corpus Christi, TX
    Posts
    88
    Thank you for the help and explaining what is going on. Where would I declare the PHP file and Tag ID? I see your question marks, but also notice that the php_file and tagID are referenced a few times in the script. What is your opinion on placement and how to declare them?

  4. #4
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    872
    It's not really possible for me to tell you that. When the ajaxrequest() function is called, it is expecting 3 arguments: a php file to send the ajax request to, a tag id (the id of an html element on your page) and a testResult variable that holds the result from the speed test.

    The tagID will likely be 'msg' since that's the only element on your page with an id set (aside from the button). However the php_file is something you have to find out for yourself. It's a php file that will be on a server, this is where you are submitting the test results to.

    So in the end you would replace my line with question marks with something like:
    Code:
    ajaxrequest("some_file_on_a_server.php", "msg", testResult);
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  5. #5
    Join Date
    Mar 2014
    Location
    Corpus Christi, TX
    Posts
    88

    Close, but not quite

    I was able to get this script running all the way through with zero errors. However, nothing seems to copy over into the PHP file. My ultimate goal is for all the results from the speed test to be carried over into PHP which will then put those results into a MySQL database. I have confirmed that the PHP script can successfully connect to the DB. It seems as if no data is being sent to the PHP script.

    index.html:

    Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript">
    	
    	
    </script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		SomApi.startTest();
    		 
    	}
    	var php_file = 'extract.php';
    	var tagID = 'data';
    	function onTestCompleted(testResult) {
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    		ajaxrequest(php_file, tagID, testResult);
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    
    	// sends data to a php file, via POST, and displays the received answer
    	function ajaxrequest(php_file, tagID, testResult) { 
    		// create pairs index=value with data that must be sent to server
    		var the_data = 'onTestCompleted='+testResult.download.innerHTML;
    		var php_file = 'extract.php';
    		var tagID = 'data';
    		var xmlHttp = new XMLHttpRequest();
    		var request =  get_XmlHttp();
    		
    // create the XMLHttpRequest object, according browser
    	
    	var xmlHttp = new XMLHttpRequest();
    	function get_XmlHttp() {
    		// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    		var xmlHttp = null;
    		if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
    			xmlHttp = new XMLHttpRequest();
    		}	else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return xmlHttp;
    	}
    		
    request.open("POST", php_file, true);			// set the request
    		// adds  a header to tell the PHP script to recognize the data as is sent via POST
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.send(the_data);		// calls the send() method with datas as parameter
    
    		// Check request status
    		
    	}
    
    	(function(){ setTimeout(btnStartClick, 1500); })();
    </script>
    </body>
    </html>
    extract.php (connection information removed)

    Code:
    $str = $_POST['onTestCompleted']; 
     $sql="INSERT INTO data (test)
    VALUES
    ('$str')";
    I am getting the error: Notice: Undefined index: onTestCompleted in C:\xampp2\htdocs\htdocs\Speedtest\extract.php on line 12
    which is what is leading me to believe that no data is being transferred.

    Thoughts?

  6. #6
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    872
    You are probably creating issues with the variables as you declare:
    Code:
    var php_file = 'extract.php';
    var tagID = 'data';
    The problem would likely occur from those exact same variable names being used as arguments/parameters. To give you the short version on function arguments, when you declare a function and set arguments "function _Blah(arg1, arg2){}" you are having the function create new private variables each time it runs. The values of those variables are equal to whatever you pass in. But if those argument variable names are named after a variable that already exist I'd expect there to be a problem.

    You can either do this:
    Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		SomApi.startTest();
    		 
    	}
    	var php_file = 'extract.php';
    	var tagID = 'data';
    	function onTestCompleted(testResult) {
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    		ajaxrequest(testResult);
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    	
    	function get_XmlHttp() {
    		// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    		var xmlHttp = null;
    		if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
    			xmlHttp = new XMLHttpRequest();
    		}	else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return xmlHttp;
    	}
    
    	// sends data to a php file, via POST, and displays the received answer
    	function ajaxrequest(testResult) {
    		// create pairs index=value with data that must be sent to server
    		var the_data = 'onTestCompleted='+testResult.download;
    		var request = get_XmlHttp();
    		
    		request.open("POST", php_file, true);			// set the request
    		// adds  a header to tell the PHP script to recognize the data as is sent via POST
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.send(the_data);		// calls the send() method with datas as parameter
    		
    		// If the response is received completely, will be transferred to the HTML tag with tagID
    		request.onreadystatechange = function() {
    			if (request.readyState == 4) document.getElementById(tagID).innerHTML = request.responseText;
    		}
    	}
    	}
    
    	(function(){ setTimeout(btnStartClick, 1500); })();
    </script>
    </body>
    </html>
    Or you could try this:
    Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		SomApi.startTest();
    		 
    	}
    
    	function onTestCompleted(testResult) {
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    		ajaxrequest("extract.php", "msg", testResult);
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    	
    	function get_XmlHttp() {
    		// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    		var xmlHttp = null;
    		if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
    			xmlHttp = new XMLHttpRequest();
    		}	else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return xmlHttp;
    	}
    
    	// sends data to a php file, via POST, and displays the received answer
    	function ajaxrequest(php_file, tagID, testResult) {
    		// create pairs index=value with data that must be sent to server
    		var the_data = 'onTestCompleted='+testResult.download;
    		var request = get_XmlHttp();
    		
    		request.open("POST", php_file, true);			// set the request
    		// adds  a header to tell the PHP script to recognize the data as is sent via POST
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.send(the_data);		// calls the send() method with datas as parameter
    		
    		// If the response is received completely, will be transferred to the HTML tag with tagID
    		request.onreadystatechange = function() {
    			if (request.readyState == 4) document.getElementById(tagID).innerHTML = request.responseText;
    		}
    	}
    	}
    
    	(function(){ setTimeout(btnStartClick, 1500); })();
    </script>
    </body>
    </html>
    I could be wrong in either case though. But I'd say give either of those a try first and see if anything changes.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  7. #7
    Join Date
    Mar 2014
    Location
    Corpus Christi, TX
    Posts
    88

    Cannot Read Property

    I think we are almost there. I used your first example, fixed some variables, and confirmed this script is at least calling the PHP file. I am getting the error: Uncaught TypeError: Cannot read property 'download' of undefined on line 59. Line 59 reads: var the_data = 'onTestCompleted='+testResult.download;. My initial thought is that the error is brought on because the script is looking for the result before the speed test has finished. Would you agree? If so, how would I fix that?

    Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		SomApi.startTest();
    		 
    	}
    	var php_file = 'extract.php';
    	var tagID = 'data';
    	function onTestCompleted(testResult) {
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    		ajaxrequest(php_file, tagID, testResult);
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    	
    	function get_XmlHttp() {
    		// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    		var xmlHttp = null;
    		if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
    			xmlHttp = new XMLHttpRequest();
    		}	else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return xmlHttp;
    	}
    
    
    	// sends data to a php file, via POST, and displays the received answer
    	function ajaxrequest(php_file, tagID, testResult) {
    		// create pairs index=value with data that must be sent to server
    		var the_data = 'onTestCompleted='+testResult.download;
    		var request = get_XmlHttp();
    		var php_file = 'extract.php';
    		var tagID = 'data';
    		request.open("POST", php_file, true);			// set the request
    		// adds  a header to tell the PHP script to recognize the data as is sent via POST
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.send(the_data);		// calls the send() method with datas as parameter
    		
    		// If the response is received completely, will be transferred to the HTML tag with tagID
    		request.onreadystatechange = function() {
    			if (request.readyState == 4) document.getElementById(tagID).innerHTML = request.responseText;
    		}
    	}
    	
    
    	(function(){ setTimeout(btnStartClick, 1500); })();
    	
    </script>
    <h5 style="cursor:pointer;" onclick="ajaxrequest('extract.php', 'context')"><u>Click</u></h5>
    <div id="data">This string will be sent with Ajax to the server, via POST, and processed with PHP</div>
    <div id="context">Here will be displayed the response from the php script.</div>
    </body>
    </html>
    Please note that the last three lines of code are used just to show that the script is actually trying to write to the PHP file.

  8. #8
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    872
    Well in the case of your button that you added an onclick event for, the actual issue is you are not passing a 'testResult' variable into the function at all. So when it runs ajaxrequest() upon clicking the button, 'testResult' is NULL. Thus you hit your error on line 59 because testResult.download obviously can't exist.

    You shouldn't need the button to fire that event. I also notice some of your changes didn't really make sense. Like setting the php_file and tagID variables inside of the ajaxrequest() function. These variables are being passed as arguments, thus putting 'var php_file' inside of the function completely negates having those values passed into the function. As long as the speed test script itself is working then using the code below should work. Once the speed test is complete it will automatically execute the ajaxrequest() function and send all of the data necessary. I also added serveral logging lines so if you press F12 and check you're console you should see everything being logged as it hits each step of the process.

    HTML Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		console.log("The speed test is starting...");
    		SomApi.startTest();
    	}
    
    	function onTestCompleted(testResult) {
    		console.log("Speed test complete!");
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    		ajaxrequest('extract.php', 'context', testResult.download);
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    	
    	function get_XmlHttp() {
    		// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    		var xmlHttp = null;
    		if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
    			xmlHttp = new XMLHttpRequest();
    		}	else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return xmlHttp;
    	}
    
    
    	// sends data to a php file, via POST, and displays the received answer
    	function ajaxrequest(php_file, tagID, testResult) {
    		console.log("Getting ready to send ajax request...");
    		// create pairs index=value with data that must be sent to server
    		var the_data = 'onTestCompleted='+testResult;
    		var request = get_XmlHttp();
    		request.open("POST", php_file, true);			// set the request
    		// adds  a header to tell the PHP script to recognize the data as is sent via POST
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.send(the_data);		// calls the send() method with datas as parameter
    		
    		console.log("Ajax request sent!\nphp_file = "+php_file+"\ntagID = "+tagID+"\ntestResult = "+testResult);
    		
    		// If the response is received completely, will be transferred to the HTML tag with tagID
    		request.onreadystatechange = function() {
    			if (request.readyState == 4) document.getElementById(tagID).innerHTML = request.responseText;
    		}
    	}
    	
    
    	(function(){ setTimeout(btnStartClick, 1500); })();
    	
    </script>
    <div id="msg"></div>
    <div id="data">This string will be sent with Ajax to the server, via POST, and processed with PHP</div>
    <div id="context">Here will be displayed the response from the php script.</div>
    </body>
    </html>
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  9. #9
    Join Date
    Mar 2014
    Location
    Corpus Christi, TX
    Posts
    88
    Thank you, again for your help. While waiting for a response, I was able to fix a few things that you had mentioned in your above comments. I removed that link as well as a few other fixes. I implemented your code and am ending up with the same error I created on my own (I guess great minds think alike), which is: Notice: Undefined index: the_data in C:\xampp2\htdocs\htdocs\Speedtest\extract.php on line 12

    At first, I thought the data wasn't sending with the AJAX command, but your additions to the console display prove me wrong. Below is the extract.php code:

    PHP Code:
    mysql_select_db("speedtest")or die("Connection Failed"); 

    $str $_POST['the_data']; 
     
    $sql="INSERT INTO data (test)
    VALUES
    ('
    $str')";
    echo 
    $str;
    echo 
    "Tim is groovy"
    Any thoughts as to what is not set correctly?

  10. #10
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    872
    Derp, it just hit me. In your PHP file you are looking for '$_POST['the_data']' which is indeed undefined. Why? Because you are sending the following to the script: 'onTestCompleted=SomeTestResultValue'

    When you send that string via POST to the PHP file it will get a variable named 'onTestCompleted' and the value will be the value of testResult.download.

    So your PHP file should look like this:
    PHP Code:
    mysql_select_db("speedtest")or die("Connection Failed"); 

    $str = (isset($_POST['onTestCompleted'])) ? $_POST['onTestCompleted'] : ""
     
    $sql="INSERT INTO data (test)
    VALUES
    ('
    $str')";
    echo 
    $str;
    echo 
    "Tim is groovy"
    fyi, I did modify your line where $str is set so that it checks the variable first to see that it's set. If it is, it will pass that value along to write to the database. If not it will set an empty string, as to avoid errors.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  11. #11
    Join Date
    Mar 2014
    Location
    Corpus Christi, TX
    Posts
    88

    Trying to send all the data

    WOW! Thank you for your help. I was able to tweak my PHP file and get the download speed posting to the mysql database. This is coming along greatly. I can see the light at the end of the tunnel.

    Remember, my ultimate goal is to copy all the results of the speed test into the DB. While we were successful with the download speeds, I am having difficulty replicating this to copy all results. I have posted the revised script below, adding the "upload" result, just to see if I was on the right track. It appears I am not. Additionally, my PHP file now indicates that the variable "download" is undefined. Probably likely to me changing the name in the index file in my attempt to replicate our success.

    Also, when I review the console and the DB, it appears that the script is running in two different instances, thus creating two entries for a single run of the speed test.

    Where am I going wrong with this? I'd like to pull all the speed test data and put it into the corresponding columns in the DB. One entry per run of the test.

    index:

    Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		console.log("The speed test is starting...");
    		SomApi.startTest();
    	}
    
    	function onTestCompleted(testResult) {
    		console.log("Speed test complete!");
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    		ajaxrequest('extract.php', 'context', testResult.download);
    		ajaxrequest('extract.php', 'context', testResult.upload);
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    	
    	function get_XmlHttp() {
    		// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    		var xmlHttp = null;
    		if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
    			xmlHttp = new XMLHttpRequest();
    		}	else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return xmlHttp;
    	}
    
    
    	// sends data to a php file, via POST, and displays the received answer
    	function ajaxrequest(php_file, tagID, testResult) {
    		console.log("Getting ready to send ajax request...");
    		// create pairs index=value with data that must be sent to server
    		var download = 'download='+testResult;
    		var upload = 'upload='+testResult;
    		var request = get_XmlHttp();
    		request.open("POST", php_file, true);			// set the request
    		// adds  a header to tell the PHP script to recognize the data as is sent via POST
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.send(download);		// calls the send() method with datas as parameter
    		request.open("POST", php_file, true);
    		request.send(upload);
    		
    		
    		console.log("Ajax request sent!\nphp_file = "+php_file+"\ntagID = "+tagID+"\ntestResult = "+testResult);
    		
    		// If the response is received completely, will be transferred to the HTML tag with tagID
    		request.onreadystatechange = function() {
    			if (request.readyState == 4) document.getElementById(tagID).innerHTML = request.responseText;
    		}
    	}
    	
    
    	(function(){ setTimeout(btnStartClick, 1500); })();
    	
    </script>
    <div id="msg"></div>
    <div id="data">This string will be sent with Ajax to the server, via POST, and processed with PHP</div>
    <div id="context">Here will be displayed the response from the php script.</div>
    </body>
    </html>
    extract.php:

    Code:
    <?php
    $con = mysqli_connect("***");
    $download = ($_POST['download']);
    $upload = ($_POST['upload']);
    $query = "INSERT INTO data (download, upload) VALUES ('$download', '$upload')";
    if (!mysqli_query($con,$query))
    {
    die('Error; ' . mysqli_error($con));
    }
    echo "bueno";
    
    
    ?>
    Would you please tell me how I can buy you a cup of coffee for all your help?

  12. #12
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    872
    Firstly, I'm not much of a fan of coffee

    I'll start with the PHP file since this has the simplest changes. We basically just add one variable for each field you want. I also am using a conditional statement when assigning the variables (so it checks to see if it is set and if so, uses the value). Then we just edit the SQL to insert each value to its proper field.
    PHP Code:
    <?php
        $con 
    mysqli_connect("***");
        
    $download = (isset($_POST['download'])) ? $_POST['download'] : "";
        
    $upload = (isset($_POST['upload'])) ? $_POST['upload'] : "";
        
    $latency = (isset($_POST['latency'])) ? $_POST['latency'] : "";
        
    $jitter = (isset($_POST['jitter'])) ? $_POST['jitter'] : "";
        
    $testServer = (isset($_POST['testServer'])) ? $_POST['testServer'] : "";
        
    $ip_address = (isset($_POST['ip_address'])) ? $_POST['ip_address'] : "";
        
    $hostname = (isset($_POST['hostname'])) ? $_POST['hostname'] : "";

        
    $query "INSERT INTO data (download, upload, latency, jitter, testServer, ip_address, hostname) VALUES ('$download', '$upload', '$latency', '$jitter', '$testServer', '$ip_address', '$hostname')";
        if(!
    mysqli_query($con,$query)) die('Error; ' mysqli_error($con));

        echo 
    "bueno";
    ?>
    Now for the page itself. There were a few changes I had to make, and I also removed the console logging lines because they shouldn't be needed anymore.

    The biggest change I made was putting all of the testResult data in one ajax call. When you want to send multiple variables to a PHP script you just use '&' between each name/value pair. The next change was in how the testResult data gets passed to the ajaxrequest() function. Before I had changed things to pass testResult.download directly to the function. Instead, I'm not passing the entire testResult object so you can pull all of the values at once.

    In the end the main part of the code looks like this:
    HTML Code:
    <html>
    <head>
     	<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
    </head>
    <body>
    <h2>Rental Xpress Internet Speed Test</h2>
    
    <button id="btnStart" type="button" onClick="btnStartClick()">Start Test</button>
    <div id="msg"></div>
    <script type="text/javascript">
    	SomApi.account = "SOM5326f3c941ee5";   //your API Key here
    	SomApi.domainName = "rxserver.no-ip.biz";      //your domain or sub-domain here 
    	SomApi.config.sustainTime = 4; 
    	SomApi.onTestCompleted = onTestCompleted;
    	SomApi.onError = onError;
    
    	var msgDiv = document.getElementById("msg");
    	
    	function btnStartClick() {
    		msgDiv.innerHTML = "<h3>Speed test in progress. Please wait...</h3>";
    		SomApi.startTest();
    	}
    
    	function onTestCompleted(testResult) {
    		msgDiv.innerHTML = 
    		"<h3>"+
    			"Download: "   +testResult.download +"Mbps <br/>"+
    			"Upload: "     +testResult.upload   +"Mbps <br/>"+
    			"Latency: "    +testResult.latency  +"ms <br/>"+
    			"Jitter: "     +testResult.jitter   +"ms <br/>"+
    			"Test Server: "+testResult.testServer +"<br/>"+
    			"IP: "         +testResult.ip_address +"<br/>"+
    			"Hostname: "   +testResult.hostname +"<br/>"+
    		"</h3>";
    		ajaxrequest('extract.php', 'context', testResult);
    	}
    	
    	function onError(error) {
    		msgDiv.innerHTML = "Error "+ error.code + ": "+error.message;
    	}
    	
    	function get_XmlHttp() {
    		// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
    		var xmlHttp = null;
    		if(window.XMLHttpRequest) {		// for Forefox, IE7+, Opera, Safari, ...
    			xmlHttp = new XMLHttpRequest();
    		}	else if(window.ActiveXObject) {	// for Internet Explorer 5 or 6
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		}
    		return xmlHttp;
    	}
    
    
    	// sends data to a php file, via POST, and displays the received answer
    	function ajaxrequest(php_file, tagID, testResult) {
    		// create pairs index=value with data that must be sent to server
    		var $testData = "download="+testResult.download+"upload="+testResult.upload+"&latency="+testResult.latency+"&jitter="+testResult.jitter+"&testServer="+testResult.testServer+"&ip_address="+testResult.ip_address+"&hostname="+testResult.hostname;
    		var request = get_XmlHttp();
    		request.open("POST", php_file, true);			// set the request
    		
    		// adds  a header to tell the PHP script to recognize the data as is sent via POST
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.send($testData);		// calls the send() method with datas as parameter
    				
    		// If the response is received completely, will be transferred to the HTML tag with tagID
    		request.onreadystatechange = function() {
    			if (request.readyState == 4) document.getElementById(tagID).innerHTML = request.responseText;
    		}
    	}
    	
    	(function(){ setTimeout(btnStartClick, 1500); })();
    </script>
    <div id="msg"></div>
    <div id="data">This string will be sent with Ajax to the server, via POST, and processed with PHP</div>
    <div id="context">Here will be displayed the response from the php script.</div>
    </body>
    </html>
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  13. #13
    Join Date
    Mar 2014
    Location
    Corpus Christi, TX
    Posts
    88
    FANTASTIC! One thing that has me confused is that "upload" gives me a MySQL entry of 0.00. I have the column type as decimal 10,2 and changed it to decimal 10,4. I checked spelling and syntax in both scripts, but cannot find a valid reason why this isn't being entered properly. Thoughts?

  14. #14
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    872
    I guess the first thing to check would be what the actual value of upload is when it gets passed. Try adding this inside of your ajaxrequest() function (somewhere near the end of the function)
    Code:
    console.log($testData);
    Then just check the console logs to see the name/value pairs being passed so you can see the actual value of upload. With 2 decimal places it would seem like it'd be possible to see a value for even extremely low upload speeds. It's also possible that the value being passed in isn't getting treated as the proper variable type and so a value of 0 is always being passed into the database. You could try something like this:
    PHP Code:
    $upload = (isset($_POST['upload'])) ? floatval($_POST['upload']) : ""
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  15. #15
    Join Date
    Mar 2014
    Location
    Corpus Christi, TX
    Posts
    88
    Found the problem, there was a missing ampersand for the upload: "&upload="+testResult.upload+ in the ajaxrequest function.

    Thank you very much for your help. Now, on to the next process. Going to try and hash this out with the help you have already given me.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles