1

I have html form with post method. I want to pass the value of an input field in the url to the action page. I get undefined variable at first, but when I re-submit the form, I don't get undefined variable, I get the value I want. Here is the code.

<div class="col-md-6 p-2">
     <?php
        if(isset($_POST['search'])){
            $keyword =  $_POST['keyword'];
        }  
     ?>
        <form method="post" action="search.php?keyword=<?php echo $keyword;?>">
         <div class="input-group">
            <input type="text" name="keyword" class="form-control" placeholder="Enter a keyword eg: chinese">
            <div class="input-group-append">
             <button type="submit" name="search" class="form-control btn btn-success"><i class="icofont-search"></i> Search Videos</button>
            </div>
         </div>
        </form>
        <p></p>
     </div> 
1
  • Is this work ? <form method="post" action="search.php?keyword=<?php echo $keyword;?>"> Commented Jan 10, 2021 at 11:57

2 Answers 2

1

You should declare $keyword variable before the if statement.

Try this

<?php
   $keyword = null;
   if(isset($_POST['search'])){
     $keyword =  $_POST['keyword'];
   }  
?>

Or

<form method="post" action="search.php?keyword=<?php echo $keyword ?? "";?>">
Sign up to request clarification or add additional context in comments.

2 Comments

You're right. I don't get the undefined variable again.But one thing still is pending. The the text I enter in the input area doesn't show up in the url until I click the submit button twice. @Shakil Anwar
You are submitting the form with post method. You cannot see any parameters in url.
0

Problem in your example is this line <form method="post" action="search.php?keyword=<?php echo $keyword;?>"> this will return empty value in url.

you need a page to submit form in form action, so your codes should look like this:

<div class="col-md-6 p-2">
     <?php
        if(isset($_POST['keyword']) && !empty($_POST['keyword'])){ 
           echo "Please type something to search";
        }  
     ?>
        <form method="post" action="search.php">
         <div class="input-group">
            <input type="text" name="keyword" class="form-control" placeholder="Enter a keyword eg: chinese">
            <div class="input-group-append">
             <button type="submit" name="search" class="form-control btn btn-success"><i class="icofont-search"></i> Search Videos</button>
            </div>
         </div>
        </form>
        <p></p>
     </div> 

form action will pass parameters in url

And in search result page search.php :

    if(isset($_GET['keyword'])){
        $keyword =  $_GET['keyword']; //Use filter value before searching database.
        echo $keyword;
    }  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.