How to get JavaScript value in PHP?

Get JavaScript Variable Value in a PHP Variable?

  • I have this JavaScript function which is getting a value from a select option in HTML: <script type="text/javascript"> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var str=xmlhttp.responseText; var splitstr=str.split('||'); document.getElementById("txtHint").innerHTML=splitstr[0]; document.getElementById("txtval").innerHTML=splitstr[1]; } } xmlhttp.open("GET","getdetails.php?q="+str,true); xmlhttp.send(); } </script> Now, str is the JavaScript variable I want to take its value and put it into a PHP variable. I am using this, but it is not working: $grade = "<script language=javascript>document.write(str);</script>"; echo $grade; What is the correct way to do this?

  • Answer:

    PHP runs on a web server, so it will only execute when the page loads. So the above statement will not work as it runs within the function which is called after page load. To achieve what you want, you can send str to a php file via ajax call and store it in a session variable. & then whenever you need the variable call another ajax function which will retrieve the session value.

Jaiff at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.