43

First I thought that I had to convert JavaScript to PHP, but then I found out that I cannot because of server and client side executions. So now I simply want to send ONE variable

<script type="text/javascript">
function scriptvariable()
{        
    var theContents = "the variable";
}
</script>

to a PHP variable

<?php
$phpvariable
?>

That function in the JavaScript executes when let's say I click on a button.

Now I have no idea on how to assign that phpvariable to the JavaScript one to use the phpvariable to look up stuff in my database. I know I can add it to my url or some thing and refresh the page, but I would like to do it with AJAX as I might have to use this Ajax method further in my webpage.

So is there an easy way to do this without having to dump pages of code on my page to do one simple thing?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
mrbunyrabit
  • 509
  • 2
  • 8
  • 17
  • 1
    Have you looked into jQuery for implementing ajax? It takes care of most of the messy code/work. – Bryan Nov 19 '11 at 01:21
  • i have absolutely no idea what jQuery is... Ill Google that and try and find out a bit more about that. – mrbunyrabit Nov 19 '11 at 01:22
  • 4
    @Bryan Before using a library, learn how to do it. Sugar should be added after you get the tea-cup. – Zirak Nov 19 '11 at 01:24
  • 4
    @Zirak I don't necessarily agree with that. It depends on the user's needs. In the question there is a mention of wanting an easier approach, without lots of extra code, which jQuery does for you. Some people want to build cars, others just want to change the oil :) – Bryan Nov 19 '11 at 01:34
  • @Bryan, I agree with Zirak... jQuery is not the end all solution. Research can be done an a smaller JSON or Ajax library should be used for this.... check out http://www.microjs.com .... Using jQuery to ***just*** run your ajax would be like using a chainsaw to open a pop can. It's just way overkill. – rlemon Nov 19 '11 at 06:59
  • @Bryan This is not a car. This is using a hammer. I support the lazy attitude - programmers should, in fact, be lazy. However, that is something you *earn*. If you're lazy all the way through, you may be able to build cars, but you can't nail something to the wall. The right to laziness is something you earn through hard work. – Zirak Nov 19 '11 at 12:47
  • @Raynos Thanks for your input. Not sure how calling me a troll is constructive though. – Bryan Nov 20 '11 at 01:53
  • @Bryan your promoting [programming by coincidence](http://pragprog.com/the-pragmatic-programmer/extracts/coincidence) by recommending people use utilities they don't understand – Raynos Nov 20 '11 at 01:56
  • @Raynos I understand your concern. I guess we are just of different mindsets... agree to disagree. I don't see how giving someone a tool is implying I want them to use it improperly, or not learn to use it correctly. jQuery is one way of doing it, and there may be better ways. My suggestion could lead him to learn jQuery (something useful), or to copy and paste code (bad) - it's up to the user to do the "right" thing. – Bryan Nov 20 '11 at 02:01
  • @Bryan Or he can spend 10 minutes learning how to use XMLHTTPRequest and then choose an abstraction layer of his own choice. MooTools, MyLibrary, DOM-Shim, and others would be preferable over jQuery. – Raynos Nov 20 '11 at 02:06

3 Answers3

77

PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';
</script>

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];
Jordan Brown
  • 13,603
  • 6
  • 30
  • 29
  • 1
    I know im doing something wrong.... I just dont know what... This is how i inserted this code `` ` ` ` then i get this error that it is an undefined variable... Notice: Undefined index: variable in (the php bracket) any idea what im doing wrong? – mrbunyrabit Nov 19 '11 at 01:54
  • @mrbunyrabit You need to include the jQuery library in your page... otherwise the "$" variable, used by jQuery, won't be defined. Look here under "complete example" to see how to include it in your page. http://docs.jquery.com/Tutorials:How_jQuery_Works. – Bryan Nov 19 '11 at 02:02
  • To be fair, doing AJAX without some library like jQuery a path lined with death and despair. – Alex Wayne Nov 19 '11 at 06:19
  • 2
    @Squeegy Simple ajax transactions take roughly 6 lines of code – Zirak Nov 19 '11 at 12:48
46

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Grrbrr404
  • 1,809
  • 15
  • 17
3

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

Ricardo Souza
  • 16,030
  • 6
  • 37
  • 69