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

Jenny Swift
21,999 Pointshow to access javascript variable with php using ajax
Hi, I am trying to figure out how to access a javascript variable with php, in order to then store the variable in a database. This is what I've tried. I was hoping that in my ajax.php file it would display $my_variable, but it doesn't.
Here is my javascript:
var $my_variable = "something";
$.ajax({
url: 'ajax.php',
data: {x: $my_variable},
type: 'POST'
});
And here is ajax.php:
<?php echo $_POST['x']; ?>
What am I doing wrong please? How can I get my php file to display my javascript variable?
2 Answers

Jenny Swift
21,999 PointsI got it working. The answer here http://stackoverflow.com/questions/16434482/pass-javascript-variable-to-php-with-ajax-and-the-result-doesnt-show-anything helped me.

Gustavo Borges Martini
4,986 Pointscan you post your code????

Jenny Swift
21,999 PointsThis post is really old and I use Laravel and Angular now so I do it differently to before, so sorry, I'm not sure exactly what I did back then. But if you post your code perhaps I can help...

Salma Alshabib
2,957 Pointsthis may help you: https://www.youtube.com/watch?v=woNQ2MA_0XU

Jenny Swift
21,999 PointsHi Salma and thanks for your input. :) I got it working 2 years ago but hopefully your comment will help someone!