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

how 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

can you post your code????

This 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...

Hi Salma and thanks for your input. :) I got it working 2 years ago but hopefully your comment will help someone!