Set JavaScript file to a variable in PHP - javascript

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:
PHP generates HTML (wich includes the JS code)
HTML is sent to the browser
The browser renders the HTML and executes the JS
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?

Related

jquery countdown in dynamically created html

i need a little help using the jquery countdown keith wood - jquery countdown plugin
I am creating several countdowns by retrieving data from mysql database (php ajax call) and putting it into a div:
in php (getdetails.php -> gets $mid and $time from mysql-database):
$mrow="TimeCounter inserted here:"
$mrow.="<div id=\"RowDiv\"><div id=\"timecount".$mid."\"><script> $('#timecount".$mid."').countdown({until: ".$time."}); </script></div></div>";
$mrow.="TimeCounter ends here";
in JS i set the innerHTML with the data i got:
var url="getDetails.php";
var what="getTimeData";
console.log("call getTimeData");
var p1 = $.post(url,{what:what,selId:selValue,conName:"GId"});
p1.done(function(data){
console.log("Data -> : "+ data);
document.getElementById("CounterDiv").innerHTML=data
});
console.log(data) shows me the set html:
<div id="RowDiv" ><div id="timecount2"><script> $('#timecount2').countdown({until: 1454713200}); </script></div></div>
I get no errors but i dont see the counter... I do see the surrounding TimeCounter inserted here: TimeCounter ends here on the page. I suppose it is a client / server side issue. Maybe i need to call the function again after setting the innerHTML with the data. But i dont know how.
How can i solve this? Any ideas?
Instead of adding an inline script within your HTML element, you can initiate the counter within your callback/success function of jQuery.post(). In order to do this, you will have to change your PHP and JS like below:
PHP
$mrow="TimeCounter inserted here:"
$mrow.="<div id=\"RowDiv\"><div id=\"timecount" . $mid . "\" data-time=\"" . $time . "\"></div></div>";
$mrow.="TimeCounter ends here";
JS
var url = "getDetails.php",
what = "getTimeData";
$.post(url, {what:what,selId:selValue,conName:"GId"}, function(data){
$('#CounterDiv').html(data).find('[id^="timecount"]').countdown({until: $(this).data('time')*1});
});
UPDATE:
I don't know the plugin, but the scope of this might get changed when .countdown() is called. In such a case, you can use .each() function of jQuery to pass the element. Here is how you do that:
$.post(url, {what:what,selId:selValue,conName:"GId"}, function(data){
var $counters = $('#CounterDiv').html(data).find('[id^="timecount"]'),
$el,t;
$counters.each(function(index,element){
$el = $(element);
t = $el.data('time')*1;
$el.countdown({until: t});
});
});
Haven't tested the code but the point of my suggestion would be to avoid sending HTML in response and make getdetails.php respond with $mid and $time like:
$data = array(
'mid' => $mid,
'time' => $time
);
$response = json_encode($data);
Your JS code should look something like:
var url = "getDetails.php";
var what = "getTimeData";
console.log("call getTimeData");
$.post(url, {what: what, selId: selValue, conName: "GId"}, function (data) {
console.log("Data -> : " + data);
var id = 'timecount' + data.mid;
var row = '<div id="RowDiv"><div id="' + id + '"></div</div>';
$("#CounterDiv").html(row);
$('#' + id).countdown({until: data.time});
}, 'json');

how to send javascript variable to php mysql [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to insert javascript varaible to php mysql, but it is not inserting. it is inserting as <javascript>document.write(window.outerWidth); </javascript> x <javascript>document.write(window.outerHeight); </javascript>. but the result is 1366 x 728
What should I do?
<?php
$width = " <script>document.write(window.outerWidth); </script>";
$height = " <script>document.write(window.outerHeight); </script>";
$xex = " x ";
$resulteee = "$width $xex $height";
echo $resulteee;
?>
AJAX is a good solution to your problem :
<script type="text/javascript">
function call_ajax () {
var width = window.outerWidth;
var height = window.outerHeight;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("abc").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "a.php?height="+height+"width="+width, true);
xmlhttp.send();
}
</script>
and on the page a.php, you can echo your variables to get the output like this :
<?php
echo $_POST['height'];
echo $_POST['width'];
die;
The best way is AJAX, which is a way for Javascript to send data to a PHP script. You should do some research on your own, but your solution will end up looking something like this. I'm using jQuery syntax, which is a really helpful Javascript library that I recommend looking into.
// get values we want
var width = window.outerWidth;
var height = window.outerHeight;
var payload = {"width" : width, "height" : height}; // just a normal object
// send them to server
$.get('/path/to/script.php', payload, function(response) {
alert('Sent the values!');
});
And in your PHP:
<?php
$width = $_GET['width'];
$height = $_GET['height];
/*
* DEFINITELY sanitize these things before they're anywhere NEAR the database!
* research "prepared statements" and "mysqli escape" or you are going to have a very bad time with a hacked server
*/
// do some database stuff!
Hopefully this gives you a good starting point. You really need to make sure you sanitize data before you blindly let it touch a database query or attackers can easily perform a SQL Injection attack, deleting your database or dumping all your data. These are very bad things.
You'll have to send it to a separate php file to insert it into MySQL... You'll also have to use Ajax. Include the jquery plugin in your page for that.
So this would include this in your main page. Call the submitstuff() function when the button is pushed instead of submitting a form like normal:
<script>
function submitstuff(){
var wheight = window.outerHeight;
var wwidth = window.outerWidth;
var results = wwidth+" x "+wheight;
$.ajax({
url : "submit.php",
type: "POST",
data : "result="+results,
});
}
</script>
Then, make a file called submit.php and put it in the same folder as your main file.
submit.php
/* include all your database connection stuff */
mysql_query("insert into `yourtable` (`size`) values ('".$_POST['result']."');");
I didn't test this, but I think it might work... :)
Try jQuery's $.post
var width = x;
var height = y;
$.post( "page.php", // name of the page you want to send the variables
{width:width,height:height}, // variables
function( data ) { // returned values from the page
alert(data);
}
);
You can get the variables using $_POST['width'] and $_POST['height'].

Get data from Javascript to PHP

I want to get data from javascript function (someone created this function before, and I need to get the data from this function):
Here are the javascript function:
function edit(a,b,c,d,e,f,g,h,i,j,k,l){
document.getElementById("frm").id.value=k;
document.getElementById("frm").name.value=a;
document.getElementById("frm").username.value=b;
document.getElementById("frm").emid.value=c;
document.getElementById("frm").dob.value=d;
setCheckedValue(document.forms['frm'].elements['gender'],e);
document.getElementById("frm").job.value=f;
document.getElementById("frm").info.value=g;
document.getElementById("frm").datejoin.value=h;
document.getElementById('locid').value=i;
document.getElementById('deptid').value=m;
var params = encodeURIComponent(document.getElementById("frm").username.value=b);
window.location.href="http://192.168.1.5/eleave/employee.php?lapplicant=" + params;
}
at PHP file I will use b.
This is the button who calls edit():
The code of that button are bellow:
<td align=\"center\">$uname</td><td align=\"center\">$loc1</td><td align=\"center\">$dept</td><td align=\"center\">$date</td><td align=\"center\"><button class=\"btn btn-mini\"data-toggle=\"modal\"href=\"#long\"
onClick=\"javascript:edit('$name','$uname','$emid','$dob','$gender','$job','$info','$datejoin','$locid','$deptid','$myid','$templatelist','newbal');\"><i class=\"icon-pencil\">
I've tried this javascript function in a new file:
function test_function() {
var width = 8;
var height = 9;
window.location.href="http://localhost/belajar/get_test.php?width=" + width + "&height=" + height;
}
and simply call in the PHP file such as:
<?php
$width = $_GET['width'];
$height = $_GET['height'];
print($width . " " . $height);
?>
I want to get b in edit() and use it in PHP file. I've tried to use the 2nd part in edit function. But, it doesn't work. Any idea?

How do I fetch PHP script output from Javascript?

This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/

html session timeout in progress bar

I am facing some difficulties while get the proper code to show the session timeout count down in the progress bar in my html page.
Can any one help me in doing this.
Thanks
I searched over internet and found one example on how can be this done. Here is one simple example - $inactive variable is session expiracy time, e.g. 600 seconds):
function start_onload(){
var expire_time = new Date().getTime() + 1000*<?php echo $inactive; ?>;
countdown_session_timeout();
function countdown_session_timeout() {
var current_time = new Date().getTime();
var remaining = Math.floor((expire_time - current_time)/1000);
var timeout_message = document.getElementById('timeout_message');
if (remaining>0) {
timeout_message.innerHTML = 'Session will expire in '+ Math.floor(remaining/60) + ' min. ' + (remaining%60) + ' sec.';
setTimeout(countdown_session_timeout, 1000);
} else {
timeout_message.innerHTML = 'Session expired.';
}
}
}
Php script here: http://pastebin.com/Dik0hyYd (those sessions are only as example.)

Categories