-3

I am beginner on coding I need help on passing jquery variable to php inside the same jquery

<script language="javascript">
$(document).ready(function(){
$("#option1).change(function(test));
$("#option2).change(function(test));

function(test){
var select1 = $("select1").val();
var select2 = $("select2").val();

var phpselect1 = '<?php $select1 = '+select1+'?>';
var phpselect2 = '<?php $select2 = '+select2+'?>';
}
});

</script>

I want to pass the the jquery variable to php in this way but I can't pass it anyway. Is there any way to pass the variable like this to php? please help me. ...

  • 1
    pass client side value to server side variable. **the answer is ajax** – mamdouh alramadan Mar 02 '14 at 06:10
  • PHP will run in the server and Javascript in the browser. They're disconected. What you can do is an Ajax request (javascript) that sends what you need back to the server (PHP), processes somthing if needed and returns it, if needed. – D. Melo Mar 02 '14 at 06:12
  • possible duplicate of [Reference: Why does the PHP (or other server side) code in my Javascript not work?](http://stackoverflow.com/questions/13840429/reference-why-does-the-php-or-other-server-side-code-in-my-javascript-not-wor) – Jonathan Lonowski Mar 02 '14 at 06:13

3 Answers3

2

Here is an example

AJAX:

var select1 = $("select1").val();
var select2 = $("select2").val();

$.ajax({
   url: 'yourphpfile.php',
   data: {data1 : select1, data2 : select2},
   type: 'POST',
   success:  function(data){
      //do something with the returned data
   }
});

Server-side PHP (yourphpfile.php). To assign a value passed from AJAX, do the following;

$phpselect1 = $_POST['data1']; //should be value of select1 from JS
$phpselect2 = $_POST['data2']; //should be value of select2 from JS
brenjt
  • 15,997
  • 13
  • 77
  • 118
coder29
  • 175
  • 6
1

PHP is handled server side (step 1). Javascript is done on the client-side (step 2). You're trying to tell the page to do something on the step that has already been done.

Also, you're trying to assign PHP variables using JS? If you need data to get to PHP, use GET/POST variables and pass relevant data to the PHP upon a page load/refresh.

1

You are doing it wrong. You need to use Ajax to send a Get or Post request to the server. In that request you can put your variable.

Mostafa Shahverdy
  • 2,687
  • 2
  • 30
  • 51