-3

I have a PHP file, having HTML and JavaScript code also, I want to use the javascript variable value in the php code, Sample code is as follows:

<script>
function dropdown(){
var e = document.getElementById("im_position");
var strUser = e.options[e.selectedIndex].value;
}
</script>
    <?php
$q = //here want to use strUser(javascript varible); 
?>

How do I use it ? Help me..

1

2 Answers 2

1

You can't access to javascript variable like that. PhP is execute by the server and JavaScript by client.

You can create an ajax function in JS who call your php script.

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

Here you can learn to use Ajax.

JS

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      xhttp.responseText // return from your php;
    }
  };
  xhttp.open("GET", "yourphp.php?variable="+yourjsvariable, true);
  xhttp.send();
}

Php

<?php

return $_GET["variable"]; 

?>
Sign up to request clarification or add additional context in comments.

1 Comment

can you tell me how to write ajax function for this scenario
0

You can't.

Php runs server-side. Javascript runs client-side.

This means that php compiles into html and does not reach the client. Javascript runs on the client's browser.

Your best solution would be to use ajax.

4 Comments

how do i use ajax here can you tell me
W3schools would be a great start to learn ajax.
Don't use W3schools; use a better, more trusted source, like the MDN: developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/…
What site is better is subjective, one prefers the MDN, another may prefer another website. I just gave him a link to get started and in my opinion W3schools is good at teaching basic things to (unexperienced) developers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.