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?

share|improve this question

what purpose does it have, u know that php normaly is executed before the javaskript code. or if u use ajax its called by get or post anway – Dukeatcoding Sep 4 at 10:05
Use ajax for sending javascript variable to php. – Santhiya Sep 4 at 10:06
Does not work like this. Use AJAX. – Endy Sep 4 at 10:07
feedback

3 Answers

up vote 2 down vote accepted

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'];
?>
share|improve this answer
how can I do this into jQuery? – WebDesigner Sep 4 at 10:13
updated my answer – Mihai Iorga Sep 4 at 10:23
perfect great solution and works! – WebDesigner Sep 4 at 10:25
feedback

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/

share|improve this answer
feedback

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.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.