Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a value from an HTML select to PHP with JavaScript

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.

like image 737
Genic Avatar asked Apr 25 '26 18:04

Genic


1 Answers

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.

like image 60
Mo3z Avatar answered Apr 27 '26 07:04

Mo3z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!