Passing URL variable via HTML form submission using either PHP or JavaScript

23,600

Solution 1

You will need to change the form method from POST to GET and also rename the text input from tZip to zip otherwise your URL will look like this:

http://www.mydomain.com/dealers.php?tZip=55118

instead of

http://www.mydomain.com/dealers.php?zip=55118

Solution 2

Change the form method to "get"

Share:
23,600
Brian Larson
Author by

Brian Larson

Updated on August 03, 2020

Comments

  • Brian Larson
    Brian Larson over 3 years

    I need to simply pass a form variable into a URL variable. I suspect that it's something easy to do but I'm having a hard time finding clear steps (that aren't tons of code) online anywhere.

    Here's my current form code

    <form id="zip_search" method="post" action="dealers.php">
        <label for="zipfield"><a href="dealers.php">Find a Dealer</a></label>
        <input name="tZip" type="text" id="zipfield" value="ZIP CODE" onblur="if(this.value=='') this.value='ZIP CODE';" onfocus="if(this.value=='ZIP CODE') this.value='';" />
        <input type="image" value="Submit" class="submitbutton" src="/images/submit_button.gif" />
      </form>
    

    And all I need is for it to send the browser to something like this:

    http://www.mydomain.com/dealers.php?zip=55118
    

    Thank you in advance for any help.


    Update to question

    Thanks to Drew and Anton's responses here's an update. Changing the input name attribute to match the URL var name (tZip to zip) along with changing POST to GET did the trick but for some reason it's adding two additional URL variables as well (&x=0&y=0). I'm guessing this is something incorrect with my PHP code as I'm not a PHP wizard by any stretch. Here's all the code:

    PHP Function

    <?php
    function processForm() {
        $zipCode = $_GET['zip'];
        $url = "dealers.php?zip=" . $zipCode;
        header("Location: $url");
        exit;
    }
    ?>
    

    Form

    <form id="zip_search" method="get" action="dealers.php">
        <label for="zipfield"><a href="dealers.php">Find a Dealer</a></label>
        <input name="zip" type="text" id="zipfield" value="ZIP CODE" onblur="if(this.value=='') this.value='ZIP CODE';" onfocus="if(this.value=='ZIP CODE') this.value='';" />
        <input type="image" value="Submit" class="submitbutton" src="/images/submit_button.gif" />
      </form>
    

    URL Output Example

    http://www.domain.com/dealers.php?zip=12345&x=0&y=0
    

    Additional Related Question

    How is this working if processForm() is only defined but not called anywhere else. It seems to me that the processForm() function should be in the action attribute in the opening form element. Any insight? Thanks in advance.