1

I just want to know if sending value of a javascript to php is possible. here is the simple code of what i am trying to say.

<script language="javascript" >
var id = "data"
</script>

<?php
$getthevalueofid = var id;
?>

thanks!

jonas
  • 5,259
  • 4
  • 16
  • 11
  • Your PHP code on that page is long finished executing by the time the JavaScript runs client-side. – Brad Apr 25 '13 at 03:01
  • thank you for answering. do you have any suggestion as to how i am going to solve it? I have this javascript variable value, and i really need to use it on my PHP code. – jonas Apr 25 '13 at 03:07
  • Hi, Jonas. Check out this previous post to see if it answers your questions. http://stackoverflow.com/questions/9789283/how-to-get-javascript-variable-value-in-php – Carth Apr 25 '13 at 03:21
  • 1
    @jonas, Solve what? You haven't posted your actual problem... just your attempt at fixing it. You're asking the wrong questions. You didn't even tell us what you are trying to do. – Brad Apr 25 '13 at 03:28

3 Answers3

5

Not the way your code sample is structured, no. PHP is a server-side language and Javascript is a client-side language. PHP is out of scope by the time any client-side script executes.

If you need to pass an object from the browser to your server you can use XMLHttpRequest (commonly referred to as AJAX).

Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
  • thank you for answering. do you have any suggestion as to how i am going to solve it? I have this javascript variable value, and i really need to use it on my PHP code. Thanks! – jonas Apr 25 '13 at 03:04
  • @JonasFabriag - If you need the browser to pass data to your server, you have two options: having the user submit a `
    ` or use AJAX. There are a plethora of examples of how to do this on StackOverflow. Here is one that might get you started: http://stackoverflow.com/questions/5004233/jquery-ajax-post-example
    – Justin Helgerson Apr 25 '13 at 03:07
  • thank you! I'll try to study that one. – jonas Apr 25 '13 at 03:10
2

To send a Javascript variable back to PHP, you need to do an AJAX request:

<script language="javascript" >
xmlhttp.open("GET","getvalue.php?id="+id,true);
xmlhttp.send();
</script>

And in getvalue.php you'd have:

<?php
$getthevalueofid = $_GET['id'];
?>
0

No way to do this. Use Ajax to pass javascript variable to php

Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70