3

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.

4 Answers 4

3

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.

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

1 Comment

I used this example.Thank you moiz.
1

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 );
?>

1 Comment

The thing is that i don`t want to be in a form, only in a select, but thanks for the reply
0

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);

Comments

0

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
   });
}

1 Comment

Thank you for the replyes guys. I used the simple Ajax response, i`m also new to Jquery. Thank you again for the replyes

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.