The HTML with the select value is:

<select id="value_select" onchange="get_value_js()">
<option>Value 1</option>
<option>Value 2</option
</select>

The JavaScript code:

function get_value_js() {
var the_value = document.getElementById("value_select").value;
}

I don't know how to continue the JavaScript to send the value to, for example, work.php. In work.php, I want to store the value in a PHP variable.

link|improve this question

feedback

4 Answers

up vote 2 down vote accepted

You can use AJAX.

function get_value_js(){
  var xmlhttp;
  var e = document.getElementById("value_select");
  var the_value = e.options[e.selectedIndex].value;
  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)
      {
      //Do whatever with xmlhttp.responseText;
      }
    }
  xmlhttp.open("GET","work.php?val="+the_value,true);
  xmlhttp.send();
}

You can use $_GET['the_value'] to grab the value.

link|improve this answer
I used this example.Thank you moiz. – Nebunel Jan 2 at 22:54
feedback

You could either send it as an AJAX call if you want to stay on the same page or perform a redirect and pass the value as query string parameter:

window.location.href = '/work.php?value=' + encodeURIComponent(the_value);
link|improve this answer
feedback

You need to enclose the <select> in a <form> tag like so:

<form id="myForm" method="post" action="work.php">
    <select name="value_select">
        <option value="1">Value 1 text</option>
        <option value="2">Value 2 text</option
    </select>
</form>

Please note that i've added value attributes to the <option> tags & added a name attribute to the <select>. Next, you can submit the form in the following way:

function send()
{
    document.getElementById( "myForm" ).submit();
}

Next in work.php:

<?
    $value_select = $_POST[ "value_select" ];
    echo( $value_select );
?>
link|improve this answer
The thing is that i don`t want to be in a form, only in a select, but thanks for the reply – Nebunel Jan 2 at 22:53
feedback

Use ajax with jQuery

function get_value_js() {
   var the_value =$("#value_select option:selected").val(); 
   $.post('work.php?val='+the_value , function(data) {
        //do whatever you want with the result
   });
}
link|improve this answer
Thank you for the replyes guys. I used the simple Ajax response, i`m also new to Jquery. Thank you again for the replyes – Nebunel Jan 2 at 22:53
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.