Jump to content

Triggering PHP Variable from JavaScript Variable?


paulmo

Recommended Posts

So user gets their "state page" loaded automatically (and yes I am keeping previous dropdown option :), how to get geoip_region_name (which is working and has other dependencies on page)...

<script language="JavaScript">document.write(geoip_region_name());</script>

into a PHP variable?:

<?php $state = mysql_real_escape_string($_POST['geoip_region_name']); ?>//have also tried $_GET

Seems I need to first declare a JS variable out of geoip_region_name? How to do that? Do I put geoip_region_name in a hidden form field then getElementById into PHP?Edit: if I do put it in hidden form, I'm trying this. Am I close, or even on the right track??:

<script type="text/javascript">window.onload = function(){  document.myform.region.value = region;}</script><form name="myform"><input type="hidden" name="region" value= "document.write(geoip_region_name())"/></form>

Link to comment
Share on other sites

  • Replies 51
  • Created
  • Last Reply

OK JSG, thanks. So I'm doing this:

<input type="hidden" id="region_id"/><script>document.onload=function() {document.getElementById('region_id').value="document.write(geoip_region_name())"}</script>

The geoloc is comes from here:

<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>

Again, I need geoip_region_name to become the PHP $state variable on page load. Thanks.

Link to comment
Share on other sites

document.getElementById('region_id').value="document.write(geoip_region_name())"

That's doing the same thing, you're still setting the value of the element to the string "document.write(geoip_region_name())". I don't think you want to submit a string of Javascript code. You probably want this:document.getElementById('region_id').value = geoip_region_name();

Link to comment
Share on other sites

This doesn't do it either, unless I'm missing something syntactically. And do I need to define var = something in JS before trying to use it in PHP?:

<script>document.onload=function() {document.getElementById('region_id').value= geoip_region_name()};</script>

I'm getting

Undefined index: region
on the $state variable line because the JS and the PHP still aren't "connecting."
Link to comment
Share on other sites

First, you cannot use Javascript to communicate with the same PHP script that produces the page with the Javascript. By the time the Javascript even starts to execute, PHP is already finished. If you want to get that value to PHP for the next page, then you need to submit the form to send the value to PHP. You can also use ajax to send a value, but either way, you need to realize that by the time the Javascript even begins to execute, the PHP is long gone.

Link to comment
Share on other sites

OK JSG I'm hearing that I can't get the geoloc JS value onload into a PHP variable in the 1st (home) page, user's first visit, before they touch anything? As a last resort, please let me know if something like this has potential:

<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script> //the source<form><input type="hidden" id="region_id" value= "document.write(geoip_region_name())"> //the state</form><script type="text/javascript">function jsfunc () {var region = document.getElementById("region_id");region.submit();}window.onload = jsfunc;</script><?php $state = mysql_real_escape_string($_POST['region']); //the IMPORTANT PART!etc.

If that all isn't happenin', I was just reading about SESSION, from which this is just a snippet, and seems I'd need a proxy page as well:

<?phpsession_start(); //start PHP Session$_SESSION['jsvalue'] = $_POST['js']; //store the posted value in a php session variable?>

Could I go about things this way, and then the 1st page would load with user's "state" info?

Link to comment
Share on other sites

You need to understand how PHP and client-side code work together. This is the process to generate your page:1. The client sends a request to the web server for the page.2. The server loads the PHP script and executes the code.3. The server sends the response HTML/Javascript/CSS etc to the client.4. The client receives the response and renders the page.This is a timeline, these steps happen in order. One step finishes before the next starts. The PHP code is running in step 2. The Javascript code is running in step 4. You're looking for a way to somehow have the Javascript code in step 4 send a value to the PHP code in step 2, but unless your web browser is in a time-traveling DeLorean moving at 88mph and being powered by 1.21 GW, you're not going to be able to have the Javascript code send a value to code that ran in the past. The PHP is finished, it's no longer executing, by the time Javascript starts. No matter what you do with Javascript, you're not going to send that value to a PHP script that already finished. You may want to look into another design like something where you first detect whatever you want to detect, and then have Javascript redirect to another page (possible the same page), and send those values to PHP. The user won't see much a difference unless they notice the redirect, but the simple fact is you cannot use Javascript to send any information to the same PHP script that ran to produce the page where the Javascript is. In your case that may mean the first "page" is just a redirect, and what the user sees as the first page is actually the second request, but those are the limitations you're working with.

Link to comment
Share on other sites

You can have an include file in PHP that you include on every page which can check if the PHP variables are set, and if not then output the Javascript code to get those values and redirect. There are really two ways to do the redirect. You can either use Javascript to set a cookie on the browser with the values you want to send to PHP and then just reload the same page, or you can have Javascript build the values in a URL string and then redirect to the same page with the values appended to the URL. In PHP, in the include file, you would check if those variables are set in the session. If they aren't set in the session, then you would check the $_COOKIE or $_GET array, which ever method you chose, and if the variables are set there then you copy them to the session. If they aren't set in the session and they weren't sent to the script then output the Javascript code to get the values on a blank HTML page and quit. Otherwise, on the rest of your PHP scripts you can find the variables in the session.Since that requires Javascript, you'll want to have something like this on the otherwise-blank page to let people know if they have Javascript disabled:

<div id="message">Javascript is required to view this page.</div><script type="text/Javascript">document.getElementById('message').style.display = 'none';</script>

Link to comment
Share on other sites

OK let me please interpret some of this to better understand:

include file in PHP that you include on every page which can check if the PHP variables are set, and if not
But I already KNOW the PHP variable (from geoip_region_name) is NOT set. Can't this just be Step 1, because the variable is not set?:
then output the Javascript code to get those values and redirect.
That output will be the geoip_region_name, right? I'm confused about the term "output" here as I think document.write, which I know is not what you mean.
You can either use Javascript to set a cookie on the browser with the values you want to send to PHP and then just reload the same page,
Yes! This seems less difficult than the other option. Am I reloading as a timed auto refresh?
In PHP, in the include file, you would check if those variables are set in the session. If they aren't set in the session, then you would check the $_COOKIE or $_GET array,
As before, I'm confused why they would be in the session if we haven't gotten them from the $_COOKIE yet...and which is better, cookie or get?
if the variables are set there then you copy them to the session.
I'm guessing the cookie is set in the index.php page, and the session is in the include page? I'm copying geoip_region_name to the include page?
you'll want to have something like this on the otherwise-blank page to let people know if they have Javascript disabled:
Do I have to accommodate folks without JS? They probably won't use my site to begin with...And regarding including include.php on "every page", my app is all on one index.php page for all 50 states (as a dropdown that Deirde's Dad and Scientist so kindly helped me with). This redirect will only apply on initial visit, to redirect to user's IP address state. I have 50 states in dropdown menu that all trigger new pages (content relevant to 50 states is more accurate). So when user in Georgia (who already has GA page loaded automatically--hopefully) selects "Louisiana" from dropdown, that generates the Louisiana page, no longer the geoip_region_name page. So again, this redirect to user IP state page is only on initial visit. Thanks in advance for points of clarification.
Link to comment
Share on other sites

But I already KNOW the PHP variable (from geoip_region_name) is NOT set.
This is a file which both checks if the variable is set, and also sets if not. Remember, you're going to be including this file on every page, so no matter which link they click to get to your site it will still set the variables the first time they get there. You know it's not set the first time, and this file checks each page load. If the variables are set then the file doesn't do anything, it just moves on with the rest of the code.
That output will be the geoip_region_name, right? I'm confused about the term "output" here as I think document.write, which I know is not what you mean.
Output just means whatever PHP is sending to the browser. In one case, the "regular" case, it just outputs whatever page they went to. In the special case, where the variables aren't set, it outputs a "skeleton" HTML page with just the Javascript code on the page to get the variables and send them to PHP.
Yes! This seems less difficult than the other option. Am I reloading as a timed auto refresh?
You can use window.location.reload(true) to reload the page, it will force an update from the server for the same page. That's useful because it doesn't depend on the URL, you can output that code on any page and it will always just refresh. The W3Schools reference page for that method doesn't explain the optional parameter, but this page does:http://www.devguru.com/technologies/ecmasc...ref/reload.html
As before, I'm confused why they would be in the session if we haven't gotten them from the $_COOKIE yet...and which is better, cookie or get?
Using $_GET is more reliable than $_COOKIE, but people seldom have same-domain cookies disabled. Just remember, this is one page to both check and set the session variables. The only time you haven't gotten them from the cookie or $_GET is the first time, and that's what the file is checking for. If the variables are already set it doesn't need to do anything. The include file will look something like this:
<?phpsession_start();if (!isset($_SESSION['var_name'])){  // check if the variable is set in $_COOKIE or $_GET, or else output the Javascript to get them}?>

All of the code will be wrapped in an if statement which checks if the variables are already set. If they are set, the code doesn't do anything (there's no else statement). If they aren't set, then it checks if they were passed and sets the session, or else it outputs the code to get the values.

I'm guessing the cookie is set in the index.php page, and the session is in the include page? I'm copying geoip_region_name to the include page?
You can include this file on every page and it will work, in fact you should include it on every page. The session gets set in the include file, but you can use those variables on your other pages. Once you include the file, you know that the session variables will be set (because if they aren't, it would have redirected). So you can use your $_SESSION['var_name'] values on your pages as long as you include the file which checks and gets the values first. And yes, if they aren't set you'll need to output whatever HTML and Javascript code is necessary to get those values and set a cookie or redirect.
Do I have to accommodate folks without JS? They probably won't use my site to begin with...
Even if your site doesn't work without Javascript, you'll at least want to tell people why. Then they can enable it and use your site.
Link to comment
Share on other sites

To avoid the endless loop I revised reload to:

<script>body onload = "window.location.reload(true)"; </script>

Is this OK? Page loads. But maybe I don't need that now: I've got a 3rd party PHP geoloc script working, but I still need help defining a PHP variable from geoip_regionName:

foreach ( $nearby as $key => $array ) {		echo ($key + 1) .":<br />";		echo "\t RegionName: " . $array['geoplugin_regionName'] . "<br />";

I'm trying this:

$state = mysql_real_escape_string($_POST['geoip_regionName']); //this, or $_GET is not working

I'm also just trying to use $region_Name and $geoplugin_regionName and that's not working either. This variable is defined, among others, on the include class page. Thanks for help.

Link to comment
Share on other sites

Is this OK? Page loads.
You don't necessarily need to wait for the body to load. Just set the cookie, then reload the page. That code can either be in the head or body.
document.cookie = 'geo=geoip_region_name()';
You're still sending Javascript code as the value, that's why you see the function name when you read the cookie. You want to execute the function and get the return value, not send the function name to PHP.document.cookie = 'geo=' + geoip_region_name();The session header errors are because you're sending output at some point before starting the session. Your PHP code like this should run before you send any output to the browser. There's a post in this thread that shows you how to find the source of that error message:http://w3schools.invisionzone.com/index.php?showtopic=12509The undefined index is because you're trying to use $_COOKIE['geo'] without checking if it's set first. If it's not set, you'll get that error. The same thing probably applies to $state.
in addition to the above, do I need to wrap the geoloc src link and geoip_region_name in an HTML form for all this to work?
No. You can either set a cookie, redirect to a new URL, or submit a form. You don't need to do more than one, you're just trying to get information to PHP some way. Any of those methods will send data to PHP.
And one LAST thing regarding this, when googling "geolocation cookie", I'm reading a lot about using AJAX, in particular JQuery. Should I go down this road? THANKS!!
Not necessarily. If you think ajax is the right way to go for your situation then you can use that, but it's not necessary.
Link to comment
Share on other sites

While you were responding, I edited that message (above), as I found a manageable 3rd party PHP geolocate script. I am able to use this as a PHP variable here:

echo $geoplugin->regionName;

but not here:

$state_descrip = mysql_query("SELECT * FROM states WHERE state ='$geoplugin->regionName'");

nor any variation of $regionName, $geoplugin_regionName, etc. Yet it's in PHP somewhere, so how to use it? And thanks for explanation of the options available. I will read that errors link you provided.

Link to comment
Share on other sites

Either concatenate the string or wrap the variable in brackets.

$state_descrip = mysql_query("SELECT * FROM states WHERE state ='" . $geoplugin->regionName . "'");$state_descrip = mysql_query("SELECT * FROM states WHERE state ='{$geoplugin->regionName}'");

Link to comment
Share on other sites

Seems a similar problem as before, except now the variable is in PHP; it's echoing fine on page on page load, but it's not doing the mysql query on page load, or refresh, and I need it to. This has to happen automatically, with no buttons, etc.

Link to comment
Share on other sites

Everything is the same with the dropdown etc.; that's all working. I've just included this geolocate script metioned above and trying to get the mysql query working with the geoplugin->regionName variable, on page load, which will generate user's home state page automatically. I have a sneaking suspicion though that I'm going to have to go down the JSON or similar difficult path to make this happen. I was trying to avoid that by getting this into PHP instead of messing around with JS and cookies, which are not coming easy for me.

Link to comment
Share on other sites

everything is the same with the dropdown etc. that's all working. I've just included this geolocate script metioned above and trying to get the mysql query working with the geolocate variable, on page load, which will generate user's home state page automatically. I have a sneaking suspicion though that I'm going to have to go down the JSON or similar difficult path to make this happen. I was trying to avoid all that by getting this into PHP instead of messing around with JS.
I literally meant could you show us the revised/updated code. Note: JSON is really not that hard to 'learn', nor is passing JSON from PHP to Javascript. It was meant to be a very simple way of exchanging data between langauges, because of its text based nature.The way I see it is that the geo-locate script should get a state (onload), that state is used to get all your state data from the database, and then that's 'plugged' into the various parts of your page, like we discussed, and then the page is sent to the browser to be rendered. The dropdown would offer the option for a user to select a different state after the page has loaded, in which case you would use JSG's suggestion to test whether this isset on page load, to determine whether or not to use the passed value, or the geo-locate script value to determine the loaded state for the page. Either way, you have to have some interaction between JS and PHP, if you are using a drop down to choose a state. (onload or not)
Link to comment
Share on other sites

The geolocate code starts like this:

<?phprequire_once('geoplugin.class.php'); //this is PHP class page where variables are defined, with fetch and convert functions.$geoplugin = new geoPlugin(); $geoplugin->locate(); echo "Geolocation results for {$geoplugin->ip}: <br />\n".	"State: {$geoplugin->geoplugin_regionName} <br />\n".....etc.

The way I see it is that the geo-locate script should get a state (onload), that state is used to get all your state data from the database, and then that's 'plugged' into the various parts of your page, like we discussed, and then the page is sent to the browser to be rendered.
Yes! How to do it?? BTW that's all working GREAT with the dropdown. Thanks again for that.
The dropdown would offer the option for a user to select a different state after the page has loaded,
My thoughts precisely.
in which case you would use JSG's suggestion to test whether this isset on page load, to determine whether or not to use the passed value, or the geo-locate script value to determine the loaded state for the page.
Gulp!...sounds like Cookie-ville again. I was hoping that after the initial visit, the form would supercede the geolocate script. Anyhow please lay out the steps how I proceed from here. Thanks!
Link to comment
Share on other sites

isset has nothing to do with cookies. here's the reference on it from php.net (php.net should be the fiist stop for PHP referencing)http://us.php.net/manual/en/function.isset.phpWhen you someone submits the form, you are checking for a certain value, which is how you know to look up a state from the database. Instead, you use isset as a conditional check. If the form has been submitted, then a value isset, and thus you should use the value/state provided, else use geo_locate, i.e.

if(isset($_GET['statelink')){  //the form must have been submitted, use submitted value  $state = $_GET['statelink'];}else{  //form not submitted, use geo locate instead  //geo located code here   ....  ....  $state = geo_locate_return value();  //ideally you want to get an actual state, like it was coming from the drop down};//now use $state to execute your query and populate the page like you would normally

Link to comment
Share on other sites

I was thinking you would store the state in the session, and use that on all of your pages, and only set the session value if it's not already set. If the session value is set then you don't need to do anything extra. It's not necessary to use cookies, although it looks like you already have it set up, you could also use either the get or post methods. If PHP can get the value then it's not necessary to use Javascript at all though.What does your geolocate code output? Does it give the right state?

Link to comment
Share on other sites

hmmm, I was under the impression the geo_locate would be for initial page load, but then the user could use the drop down on the page to view different states if they wanted to. Perhaps a clearer definition of behavior from the OP is required to truly comprehend the final outcome of the 'state setter' script.

Link to comment
Share on other sites

I was under the impression the geo_locate would be for initial page load, but then the user could use the drop down on the page to view different states if they wanted to.
That is EXACTLY right. What is the misunderstanding?
Does it give the right state?
Yes! and as full name "Maine" etc. which is what I need, and that's how it's searched against column in db table. Through trial and error, I have isolated the problem to this section of code:
if(isset($_GET['statelink'])){   //this is working 	$state = $_GET['statelink'];   //working, triggers query, etc. }else{  $state = $_POST['$geoplugin->regionName'];  /*or $_GET, not working, OR, it's just not "triggering" the query the way 'statelink' is triggering the query, because the latter comes from a form? I've also tried it without $, and ['" .$geoplugin->regionName . "'] etc...*/};

And to clarify, this DOES work:

echo $geoplugin->regionName;

And I am getting no errors.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.


×
×
  • Create New...