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

JavaScript

JavaScripy, JSON, AJAX and PHP help

Hello, I am building a website to improve my programming confidence. I'm making great progress, but there is just one problem I can't seem to over some.

I have two variables in JavaScript that I require to access in a PHP file when a form is submitted to that PHP file. I have tried numerous attempts using various methods and I just keep failing.

2 Answers

Have you tried using the php inside the javascript like:

<script type="text/javascript">
       var message = 'start';
       <?php if(isset($_GET['message']) && $_GET['message'] != '') { echo "message = '".$_GET['message']."';\n"; } ?>
       alert(message);
    </script>

Hi Ron, that did work but in the case I am trying to implement the Javascript is in a separate file to the PHP. I don't know if you could give any advice on this could you? I have tried using various AJAX and JSON methods (all work when working with the same file), but I cannot get them to work with separate JS files to PHP and then being able to use the PHP once it's been passed back to the server.

Hi Ron, that did work but in the case I am trying to implement the Javascript is in a separate file to the PHP. I don't know if you could give any advice on this could you? I have tried using various AJAX and JSON methods (all work when working with the same file), but I cannot get them to work with separate JS files to PHP and then being able to use the PHP once it's been passed back to the server.

You can make your external javascript file a PHP file. Then that javascript can be dynamic every time you call it. Here's a post talking about how to do that: http://bit.ly/dynamic-javascript-with-php

PROS: 1) you can have javascript that is dynamically generated based on the php CONS: 2) your javascript can not be cached causing potential performance issues. 2) mixing front-end and back-end code can open up security risks.