user1638362
user1638362

Reputation: 579

How To Get HTML Select Option Text And Post To PHP Variable Using Jquery/Ajax

HTML

<form method="post">
    <select name="MySelect" onchange="run(this)">
        <option value="year 1">year 1</option>
        <option value="year 2">year 2</option>
        <option value="year 3">year 3</option>
    </select>
</form>

I am trying to get the selected option text and store this in a php variable. To use later down the page.

The onChange event calls the run() function. In my script.js file.

Js/Ajax

function run(sel) {

    var i = sel.selectedIndex;
    alert(i);
    alert(sel.options[i].text);
    if (i != -1) {

        $.ajax({
            type: "POST",
            url: "home.php",
            data: { opValue : sel.options[i].text},
            success: function(data)
            {
                alert(data);
            }
        });
    }
}

The data opValue gets stored in the $_POST array. Then below i am trying to print the array, store in variable

Home.php

<?php
       print_r($_POST);
     if(isset($_POST['opValue']))
     {
       echo 'set';
       print_r($_POST);
       $option = $_POST['opValue'];
       echo $option ;
     }
?>

Though it doesn't work, it doesn't reach the echo set. Which suggest the post variable is not being set. What am i doing wrong here, this is fairly new to me and i am still a beginner in php/ajax/js.

P.S i have opted to do it this way as i do not want the page to reload/refresh.

regards.

EDIT:

  1. Added alert(data)

Now when i select year 2 in the response i am receiving this notable info.

Array
(
    [opValue] => year 2
)
1year 2year 2Array
(
    [opValue] => year 2
)

Upvotes: 0

Views: 2488

Answers (2)

Olive
Olive

Reputation: 11

You need a function for this. Just call the function anywhere you want it to show the options.

function mySelect(){

    $optArray = array('year 1','year 2','year 3');
    $options = '';
    foreach($optArray as $items){
        $options.="<option value='$items'>" . $items ."</option>";
    }
    return $options;
}

Call the function:

<select>
  <?= mySelect() ?>
</select>

Upvotes: 1

Quentin
Quentin

Reputation: 944321

You can't see the data being echoed out of PHP because you aren't looking at the data you are getting.

Your JavaScript is accepting the HTTP response, and then alerting "Success".

Alert the data argument to the success function instead.

Upvotes: 0

Related Questions