0

I want to pass a variable javascript into variable php. I can't use $_GET or $_POST because is all loaded by the method load in jquery and I don't have any form or possbility to implement it. This is my code:

<script type="text/javascript">
 var id= "test";
</script>
<?php $_SESSION['my_page'] =?> + id;

How can I resolve It?

3 Answers3

2

2 solutions

  • you use AJAX to send your value, see jQuery.
  • you set that session variable from a submitted form as a value and process it on your script.

Eighter way you CANNOT mix javascript with PHP like that. Javascript is client side, PHP is server side.

for jQuery:

<script type="text/javascript">
    var id = "test";
    $.get('yourScript.php?id='+id);
</script>

and in yourScript.php

<?php
     session_start();
     $_SESSION['my_page'] = (int)$_GET['id'];
?>
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
1

The truth is you can't really pass them. Javascript is client-side meaning it happens on each individual computer. PHP is server-side so it happens on the server. You would have to somehow pass that variable from Javascript into the server and you could do that AJAX.

Another idea to consider is using the standard way of passing variables into different PHP documents: forms. You can make a form and use javascript to insert what you want to be submitted into the PHP server and from there you can use the $_GET or $_POST. Hope this helps.

aug
  • 11,138
  • 9
  • 72
  • 93
0

Consider using AJAX. Here is a link to some tutorials although if you are using JQuery, it can handle most of the coding for you.

http://www.w3schools.com/ajax/default.asp

From JavaScript, you can call the PHP script after the page has loaded asynchronously (meaning that it will open a connection in the background rather than changing the page). Once the PHP script has finished executing, it will return a status code that you can check for through the JavaScript. You can access the data resulting from the PHP scripts execution in the JavaScript.

If you are coding a mobile website, be aware that not all mobile phones support AJAX.

EDIT: If you would rather use JQuery, then here is a link to a good tutorial http://www.sitepoint.com/ajax-jquery/

Ren
  • 1,111
  • 5
  • 15
  • 24