1

I am trying to replicate the following:

php if statement html option value and am following the directions as suggested:

Give name to your select.

<select name="selectedValue">
    <option value="Newest">Newest</option>
    <option value="Best Sellers">Best Sellers</option>
    <option value="Alphabetical">Alphabetical</option>
</select>

In php

Example:

switch($_POST['selectedValue']) {
    case 'Newest':
        // do Something for Newest
    break;

    case 'Best Sellers':
        // do Something for Best seller
    break;

    case 'Alphabetical':
        // do Something for Alphabetical
    break;

    default:
      // Something went wrong or form has been tampered.
}

However, I am getting the following error:

Notice: Undefined index: selectedValue in C:\xampp\trial.php on line 7

Please help

4
  • please confirm if any option was selected. Commented Mar 6, 2018 at 5:37
  • 1
    the error occurs as soon as I load the page and even when I select an option, nothing changes. Commented Mar 6, 2018 at 5:38
  • 1
    $_POST is only filled in when you submit the form. It won't have any values in it when you first load the page. You need to check if the form was submitted before trying to use the parameters. Commented Mar 6, 2018 at 5:39
  • 1
    How? should I add a submit button? Commented Mar 6, 2018 at 5:44

3 Answers 3

2

if you are sending form data then you have to set method post in your form tag or if you are using ajax send it by type post and in your php file put code inside if condition after form has been posted like isset($_POST['selectedValue'])

<form method="post" action="url to your php file">
   <select name="selectedValue">
      <option value="Newest">Newest</option>
      <option value="Best Sellers">Best Sellers</option>
      <option value="Alphabetical">Alphabetical</option>
   </select>
   <button type="submit">Submit</button>
</form>
Sign up to request clarification or add additional context in comments.

Comments

0

That's happens because you don't always have the key selectedValue in your POST array.

if(isset($_POST['selectedValue'])){
   // your code
}

Comments

0

My problem was solved after adding a submit button within the form tag of HTML

<form  action="#" method="post">
    <select name="selectedValue">
        <option value="Newest">Newest</option>
        <option value="Best Sellers">Best Sellers</option>
        <option value="Alphabetical">Alphabetical</option
    </select>
    <input type="submit" style="float:left; margin-left: 2%;" name="submit" value="Search"/>
</form>

Comments

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.