user1884723
user1884723

Reputation: 47

Call a PHP script when an option is selected from a select element in HTML

At the moment I have the following markup code on my website:

<select>
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>

I want to have a PHP script in the same directory as my webpage fire when I select a particular option. How would I go about doing this? Thank you.

Upvotes: 0

Views: 120

Answers (2)

Sam
Sam

Reputation: 2917

Do an Ajax call. Here's an example. hope this helps to understand.

cheers!

Upvotes: 1

Satish Sharma
Satish Sharma

Reputation: 9625

call a ajax on change of select like this

<select onchange="javascript:callAjax(this.value);">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>

<script>
function callAjax(sel_opt)
{
   var url = "your_php_file.php?select_option="+sel_opt;

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

            var result = xmlhttp.responseText;
            // put your result where ever you want
        }
    }

    xmlhttp.open("GET",url,true);

    xmlhttp.send();
}
</script>

your_php_file.php

<?php

// your code

?>

Upvotes: 2

Related Questions