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?
Related
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');
So basically, I got a php file where I create a script in the header.
In this script, I take the value of two textbox with document.getElementByID and I concatenate them in a variable. But now, in the same script, I want to send that var to a php section to use it.
I tried the ajax way, but since the php and the javascript is in the same file, it make an error.
Here is what the script section looks like :
IN FILE.PHP
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
<?php
$parameter = command; <----- obviously not working, but that's basically what im looking for
$output = exec("someExecutable.exe $parameter");
(...)
?>
}
</script>
EDIT 1
So here it is, I tried to use ajax this time, but this isn't working, seems like i miss something. Here is the server.php:
<?php
$parameter = $_POST['command'];
$output = exec("someexecutable.exe $parameter");
$output_array = preg_split("/[\n]+/", $output);
print_r($parameter);
?>
And here is my ajax call in my client.php (in a js script):
var command = "find";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
var ajax = new XMLHttpRequest;
ajax.open("POST", "server.php", true);
ajax.send(command);
var output_array = ajax.responseText;
alert(output_array);
For some reason, it doesn't go farther then the ajax.open step. On the debugger console of IE10, i got this error : SCRIPT438: Object doesn't support property or method 'open' .
You are trying to run a serverside script in your ClientSide script,
that's never going to work.
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
If you want to do something with the data from text_1 and text_2, you should create a php file that can handle a post/get request via AJAX or a simple submit, featuring the data from those elements, and make it return or do whatever it is you want it to end up doing.
You can't use javascript variable (client) from php (server). To do that, you must call ajax.
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
//AJAX call to a php file on server
//below is example
var ajax = window.XMLHttpRequest;
ajax.open("POST", "yourhost.com/execute.php", true);
ajax.send(command);
}
</script>
And this is execute.php on server
<?php
$parameter = $_POST['command'];
$output = exec("someExecutable.exe $parameter");
(...)
?>
Alright... I pretty much changed and tested many things and I found out that the problem was the async property of the .send command. I was checking the value of the respondText too fast. Putting the third property of .open to false made the communication sync, so I receive the infos properly. I got another problem right now, but its not the same thing, so I will do another post.
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?
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/
I am getting userid from the url.
This is what I have at the moment. I want to replace the one with $userid but I don't know how. It doesn't work and I can't seem to find the right syntax, please can someone help?
function returnimages($dirname = "Photos/1")
Basically I am trying to create a photo slideshow using html, php and javascript. I had something working before I started adding php into my code. I had html and an external javascript that changes the photos and they fade in and out in a loop. I have a photo array in javascript. Right now I am trying to add php to my html. I want to be able to get userid via url and then from that get the photos from a specific path to the userid in the directory. Then I am hoping to create an array of these photos and use them in my javascript. Here is my php code embedded in my html:
<?php
$user_id = $_GET['userid'];
print " Hi, $user_id ";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And my javascript:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
//photodisplay[0].hide().fadeIn(3000);
var user = new Array();
[1, 2, 3, 4, 5];
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
var userphoto = <? echo json_encode($galleryarray); ?>;
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/1" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
My url to get userid:
http://example.com/code.php?user_id=1
Thank you for your time!
The problem is that you are always setting the dirname instead of letting calling the function set it. You could change:
function returnimages($dirname = "Photos/1") {
to
function returnimages($dirname) {
because otherwise the $dirname is always Photo/1. Then, when you call the function, use:
returnimages('Photos/'.$user_id);
You can concatenate in PHP by using the dot '.'. This will concatenate two string and then assign them to the variable $dirname. For example:
$dirname = "Photos/" . $_GET['ID'];
The variable $dirname can then be placed in the function returnimages, like:
returnimages($dirname);