3.0 beta 2

javascript and php variables

Is there any way to put javascript variables into php, and then back out?
For example, getting an image's left style variable, and then feeding it into php without reloading the page or sending the variable by get or post?

I have tried this:

<html>
<head>
<script language='javascript'>
<!--
var the_count = 0;
var the_timeout;
var la_la_la_im_not_listening= "php ";
var la3= "?";
var la2= "<";
var phpStringy= la2;
phpStringy += la3
phpStringy += la_la_la_im_not_listening;
phpStringy += " $timer";
phpStringy += "=";
phpStringy += the_count;
phpStringy += " ";
phpStringy += la3
phpStringy += ">";
document.writeln(phpStringy);
-->
</script>
</head>
<body>
<?php
echo("$timer")
?>
</html>

but I get nothing. Help?
Baskaran
April 5,
Hello, you need to learn the difference between clientside and serverside code. In order to get a variable from the server (=PHP) you need to communicate with the server. That is normally done with a POST/GET request, but can also be done by a XML request.

When you do a document.write, you are only writing text/code to the browser, the PHP code can never be executed in that way.
Ola
April 6,
u can use $_SESSION['whatevername'] variables to store your data
u first need to start a session with session_start() function then u can declare whatever variables u need they last as long as u have set the session to last in php.ini in ur WINDOWS dir or maybe when u close the browser it depends on ur "server" settings so i would set a session variable like:
session_start();
$_session['temp'] = whatever u wanna store;

then u can access it when ever u need it!!!

not a fully example sry im in a rush :D
July 18,
Hi,

here is some code, You should use this instead of GVARS and other shit. No problem to use PHP and javaScript. An advice for programmers : HAVE A LITTLE MORE FANTASY!!! ;)

Access JavaScript from PHP

<html>
<script language="JavaScript">
var JSVar = 'something from JS code';
</script>
<?php

$MyVar1 = "?><script language=javascript>document.write('Something you want');</script><?php";
$MyVar1 = str_replace("?>", "", $MyVar1);
print $MyVar1."<br><br>";

$MyVar2 = "?><script language=javascript>document.write(JSVar);</script><?php";
$MyVar2 = str_replace("?>", "", $MyVar2);
print $MyVar2;
?>
</html>


Access PHP from Javascript

<html>
<?php
$MyVar3 = "Something in PHP";
?>
<script language="JavaScript">
alert(<?php print "'".$MyVar3."'"; ?>);
</script>
</html>


Hope this helps,

Regards,

dnmes
dnmes
September 10,
Hi,
Active widgets is a genius work! im impressed. but is there any samples that uses php, i already your samples but its quite limited, is there some who could give me some samples done in php? Hope youcan give me some samples especially in manipulating columns and returning values on picked column cells. I will appreciate it very much if you can send me some samples @ vic_ilo2@yahoo.com.

hoping for your thanks!

vsb
September 20,
hello,

i'm impressed too... i thought i couldn't insert a php code between javascript tags... huh! i was very wrong about that notion..
thanks to vsb i learn a lot and made my life... simple in a way...


glennlosentes
September 20,
OK,

Maybe I'm missing the point, and really sorry if I am, BUT..

why not just write

<?
echo "<script language='javascript'>";
echo "var JSVar = 'something from JS code'\n";
echo "document.write(JSVar)\n";
echo "</script>\n";
?>

The dnmes example above doesn't pass any PHP variables, because all it's doing is writing the javascript to the client's screen, nothing else..

In the example on the page above

Set the "var JSVar" to "= screen.width" (without quotes)

print $MyVar2 MAY print 1024 (or whatever) but it's not making a PHP variable at all. Do a view source and you will see that all it's writing is .

<script language=javascript>document.write(JSVar);</script><?php

No value or string is actually passed to PHP.

Again, sorry if I missed the point, but I hate it when people try to look clever and suck people into believing their fantasies.

you CANNOT pass a JS value to a PHP variable without a) setting a JS cookie, refreshing and reading with PHP, OR b) refreshing the page and either passing a hidden form field, or a URL string amount which you then pull back out in PHP as a $_GET.

To go PHP -> JS, you're best using cookies.







RealDev
September 25,
Hint: Read about xmlhttp
Mieri
October 26,
The dnmes example above doesn't pass any PHP variables, because all it's doing is writing the javascript to the client's screen, nothing else..

Again, sorry if I missed the point, but I hate it when people try to look clever and suck people into believing their fantasies.


There's nothing wrong with what dnmes is doing. He is showing you how to dynamically construct a function in the head section of your page which will never show up on the user's script. This is an excellent work around to using cumbersome session variables.

enginerd
November 5,
I agree with enginerd. Those few lines do exactly what I want. I needed the local time on client's computer and I can do this only with javascript. Then I pass the javascript value to a PHP variable, via a form, of course! Thanks a lot, dnmes!!! I wouldn't be able to find this by myself...
Simon Templar
November 13,
$openerurl = "?><script language=JavaScript>document.write(opener.location);</script>
<?PHP ";
$openerurl = str_replace("?>", "", $openerurl);

$oppage = substr(substr($openerurl, strpos($openerurl,"=")), strpos(substr($openerurl, strpos($openerurl,"=")),"&"));

echo "$openerurl <br> $oppage<br>";
?>

After running the script on a pop up page, I got following results:

http://localhost/index.php?input=admin&&value=login
=JavaScript>document.write(opener.location);

Either i might have made some mistakes, or seems like the script works only to output/print but not work with the vars.
Sujan K Shrestha
January 5,
Ok, i missed the posts above.. now i understand. thanx. However, you can easily pass a php -> JS easily and work with the vars. just like dnmes showed. you can however do this as well:

<?PHP
$hello = 5:
?>

<script language=JavaScript>
<!--
var a = <?PHP echo "$hello"; ?>

a+=5;

document.write(a) //will produce 6

-->
</script>

Sujan K Shrestha
January 5,
sorry.. typo..
//will produce 10
Sujan K Shrestha
January 5,
Thank YOU dnmes, it was a key, to successfully continue my project, though, i have to figure out, how it works :)
Best regards from Lithuania!
ScanBiX
April 12,
I guess you people don't test in gecko (i.e., firefox, etc).
bored
June 19,
How i can retrieve records from result in PHP after firing select query?
Jitendra
June 26,
Hello,
I am trying to use the trial version . how to integrate the grid. can any one help to get the source code for it.
plz do help me out.
Khushi
July 12,
I do not think that all of your codes will work.. Here's why.. PHP will first be executed then javascript..

<?PHP
$hello = 5:
?>

<script language=JavaScript>
<!--
var a = <?PHP echo "$hello"; ?>

a+=5;

document.write(a) //will produce 6

-->
</script>


this will work because the PHP code is inside the javascript..



$openerurl = "?><script language=JavaScript>document.write(opener.location);</script>
<?PHP ";
$openerurl = str_replace("?>", "", $openerurl);

$oppage = substr(substr($openerurl, strpos($openerurl,"=")), strpos(substr($openerurl, strpos($openerurl,"=")),"&"));

echo "$openerurl <br> $oppage<br>";
?>


this code will not be executed correctly because the javascript is inside the php code..

try it..
zero
July 21,
This will enable you to display ONLY the value of the variable - NOT perform any operations on the variable...
billg97
November 2,
<?PHP
$hello = 5;
?>

<script language=JavaScript>
<!--
var a;
a = <? echo $hello; ?>;
a+=1;
document.write(a); //a=6
-->
</script>
<?
$hello= "<script>document.write(a+1);</script>"; //$hello=7
echo "<br>\nphp \$hello =".$hello;
?>;
tyd
November 2,
When working inside a javascriptfunction I have no problem accessing phpvariables and saving them in javascriptvariables.

But when working in the same javascriptfunction I can not save javascriptvariables in phpvariables. The phpvariable just contains the javascriptsyntax not the value of the javascriptvariable.

Best regards
diesel
December 9,
I don't think you can change the value of php variables via js, only the other way around. I've been trying to use js in a realtime updating script mixed with php session data and haven't found a way to get it to work.
alex
December 12,
This is exactly what I have been trying to accomplish for the past few hours, but without success.

I agree with diesel and alex, I canĀ“t find a way to perform any JS-function, "on-the-fly", within a php-script. Since the php is executed server-side, before any client-side javascript, it seems impossible to get a value from a js-function into a php-variable.

Here is my problem:

I have a php-file that has two php-variables given a static value for width and a height to an application. The application (a clients', and not my produce obviously). I get the screen width and height (or vieport of the window rather) with JS and then I am stuck, since I can't assign the js-values to these two php-variables.

Seems the only simlple solution is to put width and height into a form at another page, post-read them with php and assign them to php-session-variables. Which is a shame, because this is the only place I need them, so I would prefer do to it in this page.

I guess ajax could be another option that I will now look into.

If anyone has a better solution to what I just wrote, I' appreciate it.

Ben
December 22,
Actualy thery is good working solution besides AJAX.

Search and read about DOM's appendChild
it allows append headers to a HTML page, any JS code can be added
to a static HTML page seen at the browser at any time without reloading!!

so prepare file in PHP with JS code to run:
<?php 
  echo "var myJSvar1=$somePHPvar1 ;";
  echo 'var myJSvar2="'.$somePHPvar2.'";';
?>


and call function in JS with appendChild
PHP's prepared JS code will be fetched,executed and JS variables will change the values.

You can do everything with static HTML page without reloading by
calling JS code "on demand" from PHP script.

Hope you will find on net ready to use JS function with appendChild.
Ceasar
December 30,
I nead to store too variabels on the server side from my javascript. Becouse more then one client are going to read the variabels from the server. And my Client side javascript is going to update thes too variabels konstantly.

For exampel, if i want to store X_pos and Y_pos for my mouse-curser in too variabels on the server side. So a nother computer can read where my mouse-curser X_pos and Y_pos is.
What to do?

Reagards //dagstjerna
January 27,
You can pass a PHP variable into a javascript variable but you CANNOT pass a javascript variable into PHP - not without refreshing the page.

As your web page loads, your PHP is executing.. creating the HTML and setting up your javascript as well. Once the page has finished loading, the PHP code is effectively finished - and not used again on that page.

So once the PHP is finished after the page load, you have javascript at your disposal - not PHP - so therefore you cannot pass a javascript variable to PHP.
Geoff
January 27,
Geoff: Not true.

You CAN pass a PHP variable into a javascript variable AND you CAN pass a javascript variable into PHP - all without refreshing the page.
No AJAX requred.

I do it all the time in my web app.

Just in JS:
var jsVar1=1;
var jsVar1=2;

function ButtonClick(){
  include_rpc('my_php_script.php?phpVar1='+jsVar1+'&phpVar2='+jsVar2)
}

function include_rpc(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}


server's PHP: my_php_script.php
<?php

  echo 'var jsVar3='.($_GET['phpVar1']+$_GET['phpVar2']).';';
  echo "alert(jsVar3);";
?>


Calling ButtonClick() you will get alert with '3'.
Sum of JS vars done by PHP on server side.

Ceasar
February 10,
I have been following this discussion with A LOT of interest, but I'm still not really sure how I can accomplish what I want, if it's at all possible...

Basically, I have a php script which displays text. Wow. The idea is that the user can mouse-select (highlight) anything he wants, and that the selected text is fed into a href to, say, Wikipedia:

<?php
echo "This is some most noteworthy text.";
echo "<a href=\"http://en.wikipedia.org/wiki/\"Search your selection in Wikipedia</a>";
echo "Suppose you want to look up the word Germany, you ";
echo "could simply highlight it and click the link above.";
?>

Now, how to get the user's selection? I found a beautiful Javascript getSel() function which does this (courtesy: http://snippets.dzone.com/tag/selection) :

function getSel(){
var w=window,d=document,gS='getSelection';
return (''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
}

This function "grabs" your highlighted selection. If you put it in a string like this:
<a href="javascript:getSel();">Select something and click here</a>
a new window is opened, with your selected text, and with "javascript:getSel()" in the URL window.

My problem: how do I combine my Wikipedia href and the getSel href??? Or: how do I get the getSel() selection into my Wikipedia url????

I am moderately fluent in PHP, but I hardly know anything about Javascript, so be gentle with me :-). A working example, if at all possible, would be greatly appreciated. Thanks!!!

Ludo
Ludo
February 15,
Hmm, I forgot a ">" in the wiki url:
echo "<a href=\"http://en.wikipedia.org/wiki/\">Search your selection in Wikipedia</a>";

This is the correct one.
Ludo
February 15,
You CAN idd send javascript vairables to PHP without reloading.
My version of doing this might not be the best but hey it works.

sendJSvars = new Image(); 
sendJSvars.src = "receiver.php";


And whenever I have to save a var to Session of DB or whatever I just at get vars to sendJSvars.src like so: receiver.php?var=true

In PHP I do something like:

if(Isset($_GET[var]))
    {
        $_SESSION['vars'][] = $_GET[var];
    }
header("Content-type:image/gif");
header("Content-Disposition: attachment; filename=spacer.gif");
header("Location: images/spacer.gif");


Cheers from the NL
Hendricus
March 2,
Hendricus, that is very creative.

I don't know why you can't just use a request object (Ajax). If your using AW, then you might as well use the built in AW.HTTP.Request

var r = new AW.HTTP.Request;
r.setURL("rpc.php");
r.setRequestMethod("GET");
r.setParameter('fromJavascript', theVariable);
r.request();
r.response = function(data){
alert(data); // do something with the response
}
Its not that hard to do ajax from scratch either.

http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
Pat
March 2,
Ludo, here is an entire html file to paste
<html>
<head><title>test</title>
<script>
function getSel(){
var w=window,d=document,gS='getSelection';
return (''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
}
function followSel(){
document.location.href = 'http://en.wikipedia.org/wiki/' + getSel();
}
</script>
</head>
<body>
<p>Ad_Infinitum_Nauseum</p>

<a href="javascript:followSel();">LInk</a>
</body>
</html>
Pat
March 2,
Hi Pat,

Thank you for that :)
Well I haven't looked into AJAX as much as I should have. So I'm not sure how good the compatibility is with legacy browsers. The code above I came up with quite a while a go seems to work with a lot of browsers anyway.

But as I said, I don't know enough about AJAX. I will look into that tutorial soon mate!

Cheers
Hendricus
March 6,
i newbie in coding. i think, if we use AJAX, we can use POST and GET and we can do more with the variable and manage it and the response too, if we use js like do by Ceasar
Saturday, February 10, 2007, we just can use GET, and we have extra effort to manage the variabel and response.
winotosw
April 15,
to winotosw:
yes, but notice that POST and GET works with variables,
with my code you can fetch parts of JS code from server, moreover
after execution of JS you can _remove_ it to hide the JS's source,
just :
head.removeChild(script)
Ceasar
May 18,
Well I've spent an entire bank holiday weekend wrestling with dnmes's script. I can pass the value of JSVar to a blank page via php using...

<?php
$MyVar2 = "?><script language=javascript>document.write(JSVar);</script><?php";
$MyVar2 = str_replace("?>", "", $MyVar2);
print $MyVar2;
?>

But now stumped as to how I can use this value as part of a MySQL query. Can anyone offer any pointers?
ar_kid
May 29,
Hello guys, i was thinking on how to execute queries without refreshing the webpage and without using AJAX. The first step, is to get fields with JS and put them into php variables.

I made this script:

<script>

function recognize()
{
<? $hello = "document.write(document.form.phrase.value);"; ?>

alert('<? echo $hello; ?>');

}

</script>

<form name = 'form'>

<input name = 'phrase' type = 'text' value = 'hello, world'>

<input type = 'button' onClick = 'recognize();' value = 'Go!'>

</form>

I have a form with the input, and a button that call recognize().

recognize() will get the field's value with JS and put it in a php variable, then the alert will show the PHP variable. But this script is not working. How could i implement it? if i can, i will be able to get field's value without using $_POST.

The syntax is wrong, i tried many ways, but its not working.

Who can help me out?
Caio Dantas
June 19,
Ahojte chalani, pozerala som si par vasich rad a typov, ako sa tu neviete dohodnut, pomohlo mi to, aj ked tam bolo dost preklepov.

Comment from Slovakia
alena&michal
August 7,
I had started to be dissapointed....
My case is similar.
I want to pass to my server via php , the document.referrer (JScript variable) and i have a form to pass variables from the main page to the secondary page.

After a lot of research, the attached worked for me :

<form name="form">
<input type="hidden" name="refer" />
<input type="submit" name="sa" value="submit" />
script language=javascript>
document.form.refer.value=document.referrer;</script>
</form>



Monaxoss GR - 2007
October 17,

This topic is archived.

See also:


Back to support forum

Search

Version 2

Looking for AW 2.6 ?
The old site is here.