Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript variable to PHP 2

Status
Not open for further replies.

jebo100

Technical User
May 11, 2007
52
PH
i don't know if this is the right forum for my question.

i have a simple prompt javascript like this;
<script>var js_var=prompt('enter your name')</script>

how do i transfer the variable "js_var" to PHP variable?

ex: $myphpvar = js_var


thanks!



JEBO
4saledavao
 
there are a number of ways, none are php. php receives external variables in a number of ways including: the query string, posted data and through cookies. sp for this you could
1. send the data to php as get/post through an xmlhttprequest object (ajax)
2. by doing a document redirect and appending the variable to the url as a query string
3. by inserting the variable in a hidden form using javascript and then submitting the form
4. (potentially) by writing the data into a cookie and then refreshing the page

all of these are javascript mechanisms, so for 'how to' you should ask in the javascript forum.
 

thanks for the tips jpadie,
with almost 2 hours of tinkering, i came up with these code and it worked for my needs.

<script>;
var js_var=prompt("enter usercode");
var js_var2=confirm("click ok to continue");
</script>

<?php
$php_var="<script>document.write(js_var)</script>";
$php_var2="<script>document.write(js_var2)</script>";
echo $php_var."<br>";
echo $php_var2
// i used the $php_var variable for my mysql query
?>






JEBO
4saledavao
 
>// i used the $php_var variable for my mysql query
I wonder how possible $php_var or $php_var2 can possible contain useful info for your mysql query. It seems the "solution" is not one.
 
thanks for the comment tsuji,

i am making an admin page which will allow admin users to maintain the contents of our web site.
i used the javascript "prompt()" as the log in form.
now i have to pass the javascript variable to php variable so i can use it for my query.

<?php
$php_var="<script>document.write(js_var)</script>";
$sq=mysql_query('select * from users where usercode=$php_var');
.
.
.
thanks again.
"not really sure if this is a proper code, but it works"

JEBO
4saledavao
 
i am gob smacked that this would work. i really can't see how it can. the result of this for your query is:

Code:
$sq=mysql_query('select * from users where usercode=<script>document.write(js_var)</script>');

so for this to work accurately, the usercode would actually have to be set to the complete string <script ... not to mention that the string is not enquoted and so the mysql query would fail anyway.

as i posted above, there are only a few ways for js and php to interact. this is not one of them.

it also really does not seem sensible to use a js prompt as a means of harvesting user input when html has a perfectly good alternative: the <form> element and its controls.
 
AGREE with you guys,
i was assuming that i could use the $php_var for my query because if i echo $php_var, it returns the string i inputed from the js prompt.

but when i tested it in actual query, it didn't. :(
i dont really understand what happened.

echoing $php_var returns the value from js prompt variable.
but echoing str_word_count($php_var) returns 6.
it counts the words from "<script>document.write(js_var)</script>"

i wanted to use the js prompt as log in form because i wanted the form to be modal.

JEBO
4saledavao
 
modality does not help you particularly, because the user could simply switch javascript off.

it is better to handle access control at the server side. simply do not serve protected content to unauthorised users.

here is a very simple login script that uses a static password. obviously you can change this to use a user level equivalent, with ease. save this script to a file called, e.g. loginManager.php.

then on every page that you want to protect, add this code as the very first line of the page
Code:
<?php require_once 'loginManager.php'; ?>


Code:
<?php

define ("TIMEOUT", 600) ;// timeout in seconds
new loginManager();

class loginManager{
	public function loginManager(){
	    if (session_id() == '') session_start(); //start the session if needed
	    if (isLoggedIn()){
	        if (isset($_GET['logout'])){
	            logOut(true);
	        } else {
	            //do nothing, let script execution continue
	            return;
	        }
	    }
	    if (isset($_POST['loginpass'])){
	        //validate the password
	        if ($this->checkpassword($_POST['loginpass'])){
	            //if we have the right password then log the user in
	            $this->logIn();
	        } else {
	            $this->logOut();
	        }
	    } else {
	        $this->logOut();
	    }
	}
	//we use nonces to prevent back button/refresh resubmission of credentials
	private function checkNonce(){
	    if (!isset($_SESSION['nonce'])){
	        return false;
	    }
	    if (!isset($_POST['nonce'])){
	        return false;
	    }
	    if ($_SESSION['nonce'] !== $_POST['nonce']){
	        return false;
	    } else {
	        unset($_SESSION['nonce']);
	        return true;
	    }
	}
	private function getNonce(){
	    if (isset($_SESSION['nonce'])){
	        
	    } else {
	        $_SESSION['nonce'] = md5(uniqid(rand(), true));
	    }
	    return $_SESSION['nonce'];
	}
	private function logIn(){
		$_SESSION['lastaccess'] = time(); //sets the timer
	    $_SESSION['username'] = $_POST['loginpass'];
	    //for debuggin
	    echo <<<HTML
	logged in.  Click <a href="{$_SERVER['PHP_SELF']}?logout">here</a> to logout
	HTML;
	}
	
	private function isLoggedIn(){
	    if (isset($_SESSION['username'])){
	        if (!$this->isTimedOut()){
	            return true;
	        } else {
	            return false;
	        }
	    } else {
	        return false;
	    }
	}
	
	private function isTimedOut(){
	    if (empty($_SESSION['lastaccess'])){
	        return true;
	    }
	    if ((time() - TIMEOUT) >= $_SESSION['lastaccess']){
	        return true;
	    } else {
	        $_SESSION['lastaccess'] = time();
	        return false;
	    }
	}
	
	private function checkPassword($pwd){
	    if (!$this->checkNonce()) return false;
	    $pwd = trim ($pwd);
	    return ($pwd === 'password');
	}
	
	private function logOut($redirect = false){
	    unset($_SESSION['username']);
	    unset ($_SESSION['lastaccess']);
	    if ($redirect){
	        header('Location:'.$_SERVER['PHP_SELF']);
	        exit();
	    } else {
	        $this->displayLoginForm();
	    }
	}
	
	private function displayLoginForm(){
	    $nonce = $this->getNonce();
	    $form = <<<HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "[URL unfurl="true"]http://www.w3.org/TR/html4/strict.dtd">[/URL]
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>Login Here</title>
		<style type="text/css">
			html, body, input {font-family: verdana; color: rgb(96,87,140); padding:0; margin:0; background-color: black;}
			#contentWrapper {position:relative; top: 150px; width: 30%; margin: 0 auto; }
			#message {border: dashed #FFFFFF 1px; background-color: #FF3300; padding-top:25px; padding-bottom: 25px;color: #FFFFFF;margin-bottom: 20px; text-align: center;}
			#loginFieldset{background-color: #FFFFFF; }
			#loginFieldset .button {background-color: silver; }
			#loginFieldset .row {clear:both; text-align: center;}
			#loginFieldset .row .field{width: 60%; margin: 0 auto;}
			#loginFieldset .row .field input {background-color:#FFFFFF;}
		</style>
	</head>
	<body>
		<div id="contentWrapper">
			<div id="message">
			You are not authenticated.  Please login.
			</div>
			<div id="form">
				<form method="post" action="{$_SERVER['PHP_SELF']}" id="loginForm">
					<fieldset id="loginFieldset">
						<div class="row">
							<div class="label">
								<label for="loginPass">Enter your password</label>
							</div>
							<div class="field">	
								<input type="text" name="loginpass" class="midSize" id="loginPass"/> 
							</div>
						</div>
						<div class="row">
							<div class="buttonDiv">
								<input type="submit" name="submit" value="login" class="button"/>
							</div>
						</div>
						<input type="hidden" name="nonce" value="$nonce"/>
					</fieldset>
				</form>
			</div>
		</div>
	</body>
</html>
HTML;
	    echo $form;
	    die();
	}
}
?>
 
jebo100 said:
AGREE with you guys,
i was assuming that i could use the $php_var for my query because if i echo $php_var, it returns the string i inputed from the js prompt.

but when i tested it in actual query, it didn't. :(
i dont really understand what happened.

echoing $php_var returns the value from js prompt variable.
but echoing str_word_count($php_var) returns 6.
it counts the words from "<script>document.write(js_var)</script>"

i wanted to use the js prompt as log in form because i wanted the form to be modal.

Basically PHP and Javascript function in two different environments.

PHP code gets run first on the server. When that is all run and done, Its sent to the browser where the Javascript code is executed. At this point PHP has stopped running, and cannot do anything with the JS value.

By the time your JS content gets run PHP has long since ended execution.

When you put this in your mysql query, Javascript doesn't even get executed, because all that won't get sent to the browser until PHP is done. which is why you don't get the value from it.

Hope that makes sense.


----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
first, i'd like to thank jpadie for the code, and vacunita for enlightening me about js and php.

please correct me if my assumptions are wrong....
i am still a bit lost here:), what i really wanted to understand for now from the code below is, when i echo $php_var, it will return the js variable value.
(i assume it gets the value from js_var).

ex: if i enter "elmer001" from the js prompt and issue echo $php_var, it will return "elmer001". i take that the value of $php_var variable is now "elmer001".

then why does it fail when i use the variable for my query?


<script>
var js_var=prompt("enter usercode"); <!--enters elmer001-->
</script>

<?php
$php_var="<script>document.write(js_var)</script>";
echo $php_var."<br>"; //will return elmer001

$q=mysql_query('select * from table where usercode="$php_var"') //will fail
?>

isn't it that when a value is assign to a variable, it stays on the computers memory?


thank you very much for sharing your time...


JEBO
4saledavao
 
Are you trying to enter the user input and then run the php from it?

if so, simply create a "hidden" form, have the prompt be part of a function that writes the value to the form then submits it with a onload js submit, something like below...

Code:
<script>your function</script>
echo  "<form id=\"form1\" method=\"post\" action=\"whereyoursqlis.php\" target=\"_self\">" . 
      "<input name=\"php_var\" type=\"hidden\" value=\"$php_var\">" .    
	  "</form><br>" .
	  "<body onload=\"document.getElementById('form1').submit(); return false;\">";
}
?>

Your whereyoursqlis.php file would contain something like this

Code:
<?
$php_var = $_POST['php_var'];

$q=mysql_query('select * from table where usercode="$php_var"')
?>

<another redirect here (meta or js)>

doing it this way, your php runs AFTER the js prompt runs

 
ex: if i enter "elmer001" from the js prompt and issue echo $php_var, it will return "elmer001". i take that the value of $php_var variable is now "elmer001".

no. as vacunita points out, javascript in this context occurs ONLY at the client whereas php deals ONLY with the server side. for php to receive a variable set in javascript you need the client and the server to interact. read my first post for the various methods of creating this interaction.

the linearity of a page should not be taken to as an assumption that code in php aFTER code in js will mean that php has access to the javascript. what happens is this:

1. your browser sends a request for a page to the server.
2. the server passes the request to php (if the request is for a php page)
3. php parses the whole page and any included pages for syntax errors.
4. if ok, php then processes the whole page and then returns information to the webserver for onward handling to the browser. that is not to say that php only sends output when it has the whole page, the default behaviour is for php to send information to the browser whenever it is told to do so. webservers may interrupt this, however (see sleep() for example).

an analogy is a restaurant.

1. a waiter comes to your table to take your order.
2. he goes to the kitchen
3. the kitchen starts creating your mail
4. suddenly you change your mind and write a new order on a bit of paper on your table.
5. you're then annoyed because your original order arrives.

i.e. you MUST interact with the kitchen in order for them to be aware of your new order. you may ONLY interact in discrete chunks: you can't go talk to them in real time. Webserver requests are typically synchronous and not asynchronous.
 
In other words your echoing of your JS variable works when you just echo, because once everything is delivered to the browser your section of Js code gets executed. and displays the value.

If you look at source of you page from your browser , you'll see that what actually gets output is your JS code <script>document.write(js_var)</script>
And not the actual value from it.

That is PHP will echo that out and then the browser will run the Javascript, and produce the value.

If you are inputing that into your query, PHP is running, however Javascript has not, so your actually sending your JS code as the value for your query, instead of the actual value.








----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
WOW!!! that was a very good tutorial. :)
now i understand why.
Thank you very much for your patience in guiding me thru these.
i really appreciate it.

Thanks again "vacunita & jpadie" and to all the people here.


JEBO
4saledavao
 
jpadie described the methods one can use to do this. I personally use XAJAX and it works great!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top