...

View Full Version : Pass php variable to javascript function



MeTa
07-01-2011, 05:59 PM
Hello all

I have a big problem

I have my php like this


<?
$codid=$_GET["cid"];

echo "
<script>
setTimeout(function() {CSelect();}, 100) ;
</script>
<div id=\"ReloadThis\"></div>";
?>


And my js funtion



function CSelect()
{
var
$http,
$self = arguments.callee;


if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}

if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 10);
}
};
$http.open('GET', 'linii_c/select.php'+'?cod='+'PHP VARIABLE', true);
$http.send(null);
}

}



who i can put my php variable into the funtion?

Thanx in advence and sorry for my bad english!

Fugix
07-01-2011, 07:28 PM
1. in your javascript function, do not prepend your variables with a dollar sign ($), as this is invalid syntax for JS.

2. instead of using PHP to grab the URL parameter, you can use javascript, refer here (http://www.netlobo.com/url_query_string_javascript.html)

devnull69
07-01-2011, 10:20 PM
1. in your javascript function, do not prepend your variables with a dollar sign ($), as this is invalid syntax for JS.

No it isn't

Even most of the JS frameworks use the $ notation

Old Pedant
07-01-2011, 11:15 PM
You can put the PHP variable in place in JavaScript code. Not hard.


$http.open('GET', 'linii_c/select.php?cod=<?php echo $PHPVARIABLE; ?>', true);

Old Pedant
07-01-2011, 11:18 PM
As a minor point, though this is legal:


<script>
setTimeout(function() {CSelect();}, 100) ;
</script>

you can instead do

<script type="text/javascript">
setTimeout( CSelect, 100 );
</script>

MeTa
07-02-2011, 12:54 AM
if i put


<script>
setTimeout(function() {CSelect(".$codid.");}, 100) ;
</script>


and function



function CSelect(codid)
{
var
$http,
$self = arguments.callee;


......................
......................................................

$http.open('GET', 'linii_c/select.php'+'?cod='+codid, true);
$http.send(null);
}

}



Returd (undefined) :|

MeTa
07-02-2011, 12:58 AM
You can put the PHP variable in place in JavaScript code. Not hard.


$http.open('GET', 'linii_c/select.php?cod=<?php echo $PHPVARIABLE; ?>', true);


JS is not in php directory

devnull69
07-02-2011, 08:03 AM
I don't get it. What do you want to tell us?

Fact:
Javascript is being generated by PHP in the first place ... much the same as HTML. Something like


<?php
echo "<p>Whatever</p>";
?>
<h3>Direct HTML</h3>
<script type="text/javascript">
var myJSVariable = <?php echo $PHPVARIABLE; ?>;
</script>

And this is exactly the way to output a PHP variable to javascript



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum