Reply
How do I assign javascript variable to php variable?
Old 12-07-2004, 05:50 PM How do I assign javascript variable to php variable?
Average Talker

Posts: 25
Trades: 0
Hi, again .... Im trying to make a javascript jump menu that lists mysql databases, anyway far before completion of this I have run into a rather tricky problem!

First I will show you a extract of the code ..... the function is javascript

function getValue(form) {
var Item = form.menu1.selectedIndex;
var Result = form.menu1.options[Item].text;

document.write("index is "+Item); //index

document.write("result is "+Result); //actual contents


//I need to assign Result to phpvar
}

Pretty basic I no but the thing is I need to assign the javascript Result var to a new php $phpresult var

e.g <?php $phpresult= ?> Result , I have tried echo commands mixed with javascript doc.writes and I can manage to assign a php var to javascript var but not the other way around.I read something about having to recall the same form but I cant get the syntax correct.

Im really stuck with this

Thanks Again
David
raziel777xj is offline
Reply With Quote
View Public Profile
 
 
When You Register, These Ads Go Away!
Old 12-08-2004, 06:37 PM Cant get silly javascript variable into a php variable or vica versa..ANNOYING
Average Talker

Posts: 25
Trades: 0
ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!

This is driving me up the wall lol

I have now figured that I cant directly do what im asking but that aint much good as Im basically have a form and on load it gets populated with mysql databases e.g

<table width="254" border="1">
<tr>
<td>Show Databases</td>

<td><form name="form1" method="get" action="admin.php">
<select name="menu1" onChange="javaFunction()">
<?php
$query = 'SHOW DATABASES';
$result = mysql_query($query) or die('problem with query');
while($row = mysql_fetch_array($result)) //fetches row and moves to next
{
//echo 'row : <option selected value='$row[0]'>'$row[0]'</option>';
//at this point only row 0 is shown which is next one along
if(list($key,$value) = each($row)){

$value = getvalue($value);
$key = getkey($key);
echo "<option selected value='$row[0]'>'$row[0]'</option>";
}
}

?>

but the thing is when i user selects a database i need to grab the index or key of the database selected in the combobox and pass it to a php function and assign it to a php variable after which I can use this value to show relevant information about the selected DB but javascript is just DUMB lol.

If any one could assist in any way it would be greatly appreciated .... this is really holding me back ...... as I said I have done reading that says it cant be done directly and the stuff that I have seen to do with reloading the page has errors in it is not understandable enough that I can integrate itinto what I need to do

Please excuse the state of my code its just, Im at the stage now where im hacking aimlessly because theres no structured documentation that describes how to do this in lamens terms

Regards
David
raziel777xj is offline
Reply With Quote
View Public Profile
 
Old 12-08-2004, 06:59 PM
Kyrnt's Avatar
The Post-Mod Years

Posts: 2,535
Location: Western Maryland
Trades: 0
David, the only way that you are going to be able to get a value out of JavaScript (which runs on the client) back into PHP (which runs on the server) is by a page load. You asked how to get the JavaScript Result back into PHP. When Result is assigned a value (let's say 55), you need to make a JavaScript call to redirect the browser:

Code:
<script language="JavaScript">
var Result = 55;
location.href="myPage.php?Result=" + Result;
</script>
You can then use the $_GET superglobal array to get the value of Result.
__________________
—Kyrnt
Kyrnt is offline
Reply With Quote
View Public Profile Visit Kyrnt's homepage!
 
Old 12-08-2004, 08:26 PM Alot further forward
Average Talker

Posts: 25
Trades: 0
Thanks again Krynt, that code has been very helpful and I am very near the point I want to be, this is where im at (- the unessesary stuff)

<form name="form1">
<select name="menu1" onChange="getValue(this.form)"> //branches to jscript function here

other ----- code
</form>

<Script language="JavaScript">

function getValue(form) {
var Item = form.menu1.selectedIndex;
var Result = form.menu1.options[Item].text;

document.write("index is "+Item); //index

document.write("result is "+Result); //actual contents

location.href="admin.php?Result=" + Result; //recalls page.... is this equivalent to a GET?

document.write("<?php getdb(); ?>"); // should be jumping to php function here where i want to echo Result to make sure



}
</Script>

<?php
function getdb() {
$r = $_GET['Result'];
echo "Result of converted is ".$r; //when this line gets put in i get unterminated string constant
}
?>


Thanks for the help that has brought me a considerable amount forward..... I have one other problem as shown in the comments which is to echo the Result variable to the screen temporarly

Regards
David
raziel777xj is offline
Reply With Quote
View Public Profile
 
Old 12-08-2004, 09:25 PM
Kyrnt's Avatar
The Post-Mod Years

Posts: 2,535
Location: Western Maryland
Trades: 0
David, I am afraid that the way you have it will not work. You are trying to pass information from JavaScript to PHP in the same file and that is not possible. The only way you can do that is by sending the information back to the server. It's a question of TIME.

Realize that PHP is processed on the server. By the time the page is displayed in your browser, all the PHP has been processed and cannot be processed again. Therefore, when a user selects something on the screen and causes JavaScript to react (for example, your getValue() function being called by the onChange event), there is no more PHP. PHP only lives on the server -- so therefore, the only way to pass the value of your RESULT back to the server and have PHP do something with it is by having your JavaScript request a new page from the server using the location.href directive and to pass the RESULT value back to the server via a mangled URL (somepage.php?Result=55).

Now, following the timeline, we are back on the server processing a new page, somepage.php. PHP can read the value of ?Result=55 via the $_GET[Result] value from within PHP.

Unfortunately, in your code, you are asking the PHP be processed and the page be rendered on the client (i.e., in the browser). At this point, the server is finished and no further PHP processing can occur on this page. The user selects a choice which causes the getValue() function to run in JavaScript. Fine. But then you try to write PHP with JavaScript (which you normally would not want to do -- and can't do on the client anyway). But even if you could do that, the PHP cannot be processed because it is sitting in the browser on the user's machine. PHP must run on the server. The way you can do that is by what I described earlier -- request a new page and with it, pass the value you want your PHP scripts to know about.

I know this was a bit drawn out and redundant, but it is an issue a lot of new web programmers fail to completely understand for sometime and I hope you have gained an understanding of the distinction between client-side JavaScript and server-side PHP.

Good luck and come back with your follow-up questions.....
__________________
—Kyrnt
Kyrnt is offline
Reply With Quote
View Public Profile Visit Kyrnt's homepage!
 
Old 12-09-2004, 12:45 PM still rather stumped :D
Average Talker

Posts: 25
Trades: 0
Hi, Krynt I take it that rules out calling a php function via the onchange event as this is javascript?

I think I understand this theoretically and also the solution but I cant see what code I would do to immplement this. Have you any suggestions Krynt, however either way your help has been invaluable.

Thanks
David
raziel777xj is offline
Reply With Quote
View Public Profile
 
Old 12-09-2004, 03:12 PM
Kyrnt's Avatar
The Post-Mod Years

Posts: 2,535
Location: Western Maryland
Trades: 0
Quote:
Originally Posted by raziel777xj
I take it that rules out calling a php function via the onchange event as this is javascript?
I am afraid so -- wouldn't that be nice, though?

Now, how would you write it? On your first page, you would have the SELECT displaying the databases and the onChange event handler function -- we'll call that admin.php (I am just copying & modifying your code segments). Have it call another page admin2.php when the user selects a database and pass the parameter of the database via GET (e.g., admin2.php?Result=55):

PHP Code:
<form name="form1">
<select name="menu1" onChange="getValue(this.form)"> //branches to jscript function here
<?php
$query 
'SHOW DATABASES';
$result mysql_query($query) or die('problem with query');

while(
$row mysql_fetch_array($result)) //fetches row and moves to next
{
//echo 'row : <option selected value='$row[0]'>'$row[0]'</option>';
//at this point only row 0 is shown which is next one along 
if(list($key,$value) = each($row)){

$value getvalue($value);
$key getkey($key);
echo 
"<option selected value='$row[0]'>'$row[0]'</option>";
}
}
print 
"</select>";
print 
"</form>";
?>


// Elsewhere in the file..... JavaScript does its job

<SCRIPT language="JavaScript">

function getValue(form) 
{
var Item = form.menu1.selectedIndex;
var Result = form.menu1.options[Item].text;

location.href="admin2.php?Result=" + Result; //This causes the browser to go to admin2.php

}
</SCRIPT>
Now this is file admin2.php which will pull the value of Result out of the $_GET superglobal array -- and will now be available to your PHP scripts.

PHP Code:

<?php

$dbId 
$_GET[Result];

// Now you can have PHP go off and do another pull using the database the user selected on the previous page.
I hope this helps.
__________________
—Kyrnt
Kyrnt is offline
Reply With Quote
View Public Profile Visit Kyrnt's homepage!
 
Old 12-09-2004, 07:07 PM
Average Talker

Posts: 25
Trades: 0
Yeah that looks good, its alot easier to follow with you having integrated it into my code :-)

So what basically happens is the href causes admin2.php to open and the value result can be assigned to php there. And admin2.php is where I would need to do any database operations. This is what I required and enables me to do what I need to do. Just ot of interest is there no way I could re-call admin.php with href so that after admin.php recall I could do the desired operation there? The way I see it now thats not possible. In reference to GET,POST and the alike superglobals does another seperate page need to be called for them to be invoked as above?

Thanks Again
David

I will try what you have suggested tommorow, Im going to half a shot of half life 2 for half and hour then get some sleep :-) its getting late here
raziel777xj is offline
Reply With Quote
View Public Profile
 
Old 12-09-2004, 07:36 PM
Kyrnt's Avatar
The Post-Mod Years

Posts: 2,535
Location: Western Maryland
Trades: 0
No, $_GET, $_POST and $_SERVER, for example are available to every PHP page.

As for your other question regarding submitting BACK into admin.php, the answer is definitely. You will simply need to put some logic at the top of your file to check to see if this is the intial run of the file before the user has selected a database (in which case the expression empty( $_GET[Result] ) would be true) or if this after the user has selected a database and you have a value to work work (in which case the same expression would be false).

Take care and have a good one.
__________________
—Kyrnt
Kyrnt is offline
Reply With Quote
View Public Profile Visit Kyrnt's homepage!
 
Old 12-09-2004, 07:40 PM Prob solved Nice work
Average Talker

Posts: 25
Trades: 0
Thanks krynt I have got it working your initial way and im just going to do some more reading, thats my problem solved but look at the views lol it seems like this is a common misconception hehe

Regards
David
raziel777xj is offline
Reply With Quote
View Public Profile
 
Old 12-09-2004, 07:43 PM
Average Talker

Posts: 25
Trades: 0
Also I apologise for re-iterating some of what you told me , but ive been coding php for less than ...... 5 months approximately and I just need to get things clear in my head
raziel777xj is offline
Reply With Quote
View Public Profile
 
Old 12-10-2004, 01:16 AM
Kyrnt's Avatar
The Post-Mod Years

Posts: 2,535
Location: Western Maryland
Trades: 0
Raziel,

No apology needed -- I'm glad we got your problem solved and if you have a better understanding of web development because of the discussion -- that's just a bonus! Drop me a line if you have further questions.
__________________
—Kyrnt
Kyrnt is offline
Reply With Quote
View Public Profile Visit Kyrnt's homepage!
 
Old 12-10-2004, 06:38 PM Passing javascript variable to the same page to PHP - SOLUTION
Average Talker

Posts: 25
Trades: 0
Hi, as explained I initially used your first suggestion .... which was calling admin2.php, after I verified that the variables were being correctly passed , my stubborn side kicked in :-) wanting me to find a simplistic way to do the variable passing by calling the same page and final after many hours of toil at this, I appear to have done what I just suggested. I will submit my code as I reckon my method is a start for begginers in the same boat. I must say though this code Im sure can be done in much more elegant ways than this, but it might just help people get started.

Code:
admin.php   ---- page


<?php 

//page loads and php gets parsed and the if tests if $_GET['url']  [url variable] is set. On load of the page this will not be set so the if condition is not met and in effect this code block is ignored/skipped
if(isset($_GET['url']))
{
   $Result = $_GET['Result'];
   echo "Page was recalled and php result is ".$Result;
}
?>

<td><form name="form1">
        <select name="menu1" onChange="getValue(this.form)"> /*When user changes to a item in the jump menu by selecting it the javascript function getValue(this.form) is called 
--[now goto that function below the form]*/
		<?php

/*--php code to customise form elements this is completely irrelevant to solving the problem
--of passing a javascript variable to php*/
		?>
	    <option></option>
       </select>
      </form></td>

<script language="JavaScript">

function getValue(form) {
   var Item = form.menu1.selectedIndex;
   var Result = form.menu1.options[Item].text;
   var url; //var url is declared but not set initially
   document.write("index is "+Item); //just a way to check you
   document.write("result is "+Result); //form contents are working as anticipated
   if(url == null) { //first time around this if evaluated to true so url gets set to 1 as a flag
     url = 1;
     location.href="admin.php?Result="+Result+"&url="+url; /*This recalls admin.php and passes it variables Result and url, Result is just the contents of the selected item in my jump menu and url is the aforementioned flag which is set to 1 at this point [flag is important, anyway the page has been recalled so go to the top of the page and read the initial php code inside the if as the  condition will be met now owing to the url variable being set -- php can now use the variable because it is in a superglobal array and the page has been re-read*/

} else {

//not sure if this is necessary but put it there anyway :-)
    document.write("URL is Set Already");
}





}





</script>
My terminology may not be spot on but I think the idea of what to do is shown, also if anyone can suggest any potential problems with this or has more elegant solutions feel free to add them
raziel777xj is offline
Reply With Quote
View Public Profile
 
Old 12-10-2004, 06:47 PM
Kyrnt's Avatar
The Post-Mod Years

Posts: 2,535
Location: Western Maryland
Trades: 0
This is in line with what we talked about -- but instead of passing to another script you are passing back to the same script -- but essentially it is a second page load. Good job.
__________________
—Kyrnt
Kyrnt is offline
Reply With Quote
View Public Profile Visit Kyrnt's homepage!
 
Old 12-14-2004, 03:39 PM
Average Talker

Posts: 25
Trades: 0
Had a couple of days off there to stop my eyes going square......, agree with your last comment and ty. Even though there isnt any ground breaking code to the final solution, the fact I was initially in the dark about the way server and client side code is parsed is what made things so difficult.
raziel777xj is offline
Reply With Quote
View Public Profile
 
Old 07-05-2007, 03:39 AM Re: How do I assign javascript variable to php variable?
Junior Talker

Posts: 1
Name: sonal
Trades: 0
there is one more easy way out for this....
try this code
Code:
 <?php
if (isset($_GET['myvar'])) {
echo "My Variable is: ". $_GET['myvar'] ."<br />\n";
} else {
  // (preserve the original query string
  //   -- post variables will need to handled differently)
  echo "<script language='javascript'>\n";
  echo
location.href="<? echo $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'].'&myvar='?>"+variable;
}
?> 
i wanted to retain the query string which was having some encrypted chars so i am tried this way...
hope it's helpful to someone...
thanks..
sonalfulkar is offline
Reply With Quote
View Public Profile
 
Old 09-01-2009, 09:07 PM Re: How do I assign javascript variable to php variable?
Junior Talker

Posts: 1
Name: Abhishek
Trades: 0
This worked for me.

I didnt wanna do a page refresh.
I wanted to pass the value of a JS variable to a php function on the same page without having a page refresh or calling a 2nd php script
<script type='text/javascript'>

<?php $abc ?> = document.write(document.getElementById('report_nam e').value ); <?php ;?>;

</script>
<?php $obj1->getItem( $abc); ?>

$abc is the variable in which i get the JS variable value.
JS variable value is read using "document.getElementById"

I then pass the value of $abc in a php function as:-
<?php $obj1->getItem( $abc); ?>


Last edited by Abhiace9; 09-01-2009 at 09:11 PM..
Abhiace9 is offline
Reply With Quote
View Public Profile
 
Old 11-12-2009, 01:59 PM Re: How do I assign javascript variable to php variable?
Junior Talker

Posts: 1
Name: Alice Gheorghiu
Trades: 0
Hi Krynt. I was looking for something like that to implement a php cookie based on an error happening in java script validation. Very good job in explaining the difference btn Java script client side and php - server side aspects which was never too clear to me. I implemented in my code and it does exactly what I was looking for. Thanks God for people like you!
agheorghiu is offline
Reply With Quote
View Public Profile
 
Old 11-14-2009, 01:37 PM Re: How do I assign javascript variable to php variable?
Junior Talker

Posts: 2
Trades: 0
Hi David I am Amherstclane, the only way that you are going to be able to get a value out of JavaScript (which runs on the client) back into PHP (which runs on the server) is by a page load. You asked how to get the JavaScript Result back into PHP. When Result is assigned a value (let's say 55), you need to make a JavaScript call to redirect the browser:

<script language="JavaScript">
var Result = 55;
location.href="myPage.php?Result=" + Result;
</script>
You can then use the $_GET superglobal array to get the value of Result
__________________
sd cards
Amherstclane is offline
Reply With Quote
View Public Profile
 
Old 11-14-2009, 11:19 PM Re: How do I assign javascript variable to php variable?
freezea's Avatar
Average Talker

Posts: 27
Trades: 0
If u want to use the java script variable in php code which is reside in the same file perhaps its not possible. U write the code in separate php file, and call that file as :
window.location.href = "filename.php?Value1=" +javaScriptVariable;
and in php u can use this variable value as:
$idValue= $_GET['Value1'];
__________________
RAQ Report: Web-based Excel-like Java reporting tool.
freezea is offline
Reply With Quote
View Public Profile
 
Reply     « Reply to How do I assign javascript variable to php variable?
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML

 



Page generated in 0.17381 seconds with 13 queries