Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Marty Kunsman
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Marty Kunsman
Full Stack JavaScript Techdegree Graduate 22,262 Points

PHP passing a variable through href

Hey can anyone help me pass a variable through href and suggest a better way of doing this? I don't think this is the easiest way to pass a variable to a second page. I have a food truck site. I have a list of food trucks. A user can click on a food truck and get redirected to a location page which gives details about where the truck is currently located. I want to pass a location code from the index.php to the location.php Everything I've tried has resulted in the variable name being printed instead of the value assigned to that variable name. The echo results in the word value being printed. Any help or suggestions would be appreciated.

index.php <li><a href="location.php?var=value"><button onclick="myFunction()"><span class="truck-status"></span><span class="truck-name" id="button"></span><span class="loc-code"></span></button></a></li>

index.js var myFunction = function() { var value= "mars"; alert("value set to Mars"); var truckObj = [];
for (var i = 0; i < truck.length; i++) { if (truck[i].name == truckClick.innerHTML) { truckObj = truck[i]; var namepass = truckObj.name; alert(namepass); break; }

location.php <h1> <?php echo "Location PHP"; ?> </h1>

<?php $var = $_GET['var']; echo $var; ?>

The above echo results in the word value being printed out.

2 Answers

I'm not sure what's going on in your code but it is pretty easy to use javascript and php to send variables between web pages.

Essentially you can add an event listener to the link to the target page which appends the variable (in your case the location code) to the href property. Some thing like:

linkObject.addEventListener("click", function() {this.href += "?var=" + jsVarToSend});

Then the browser will load something like "location.php?var=someValue" which should give your PHP access to the actual value.