Jump to content

Triggering PHP Variable from JavaScript Variable?


paulmo

Recommended Posts

Help me understand. You're proposing 2 if/else statements? If so, why not if/elseif/else? Or one of those ternary deals with a switch?
I'm not sure what you're missing, I was hoping the comments would be insightful enough on their own. I am using an if/else to test if the user submitted the form, and if they didn't, then you need to use geolocate. but as it turns out, geolocate is not 'gauranteed', so just to be safe, I'm suggesting you add a function that tests the value that geolocate returns, and then based on what that function finds out, you decide whether to use it or not (i.e. use the value of $default_state instead). That is what this line
$state = (($check) ? $state : $default_state);

is doing, and it is using a ternary statement to finalize the value of $state so it can be used confidently in the query.let's review...

$default_state = "Rhode Island";  //backup in case geolocate failsif(isset($_GET['statelink'])){	//form has been submitted, so we have a valid value to use in the query	$state = $_GET['statelink'];}else{	//form hasn't been submitted, use geolocate to get users state	$state = $geoplugin->regionName;	//validateState() is a function (that you need to write) that checks if the 'state' returned by geolocate, (currently saved in the variable $state)	//is usable, i.e. one of the 50 states, and not something like Tanzania, or whatever (which would break the query)	//you pass it $state, it checks it against an array, and then returns true/false (boolean) (as an example)	$check = validateState($state);   //$check should now be equal to true or false	//if $check equals true, then we know that we can use the value of $state as returned to us by geolocate.	//if $check equals false, then we know the value of $state will break our query, so use $default_state as the fail safe	$state = (($check) ? $state : $default_state);  //this is a ternary statement, which is a shorthanded if/else statement};//now you can use $state in your query like you were already doing, and it will always 'validate' to one of the 50 states

Link to comment
Share on other sites

  • Replies 51
  • Created
  • Last Reply

Archived

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


×
×
  • Create New...