简体   繁体   中英

How to submit form using JavaScript and redirect to a URL?

How to submit form using JavaScript and redirect to a URL ?

<form name="f1" method="get" action="aaa.php">
    name : <input type="text" name="value_1" value=""/><br>
    age: <input type="text" name="value_2" value=""/>
    <input type="submit" name="submit" value="send"/>
</form>

please see image in this link:

http://image.ohozaa.com/i/4d0/zCzQIH.jpg

after press submit button , i want to redirect page to www.example.com/aaa/robert/21

How can i do that ?

Try this with html code

<form name="f1" method="get" action="aaa.php">
name : <input type="text" id="value_1" name="value_1" value=""/><br>
age: <input type="text" id="value_2" name="value_2" value=""/>
<input type="button" name="submit" onclick="checkredirect()" value="send"/>

And javascript

<script type="text/javascript">
function checkredirect(){
    var value_1 = $('#value_1').val();
    var value_2 =  $('#value_2').val();
    window.location = 'http://www.example.com/'+value_1+'/'+value_2;
    return false;
}
</script>

Don't forget to add jQuery library

set header in php file

$dynamic = $_GET['value_1'];
$id =$_GET['value_2'];
header('location:www.example.com/aaa/'.$dynamic.'/'.$id);

Try this function on click button

function myFunction() {
    document.getElementById("myForm").submit();
}

Maybe something like this:

HTML:

<form id="f1" class="js-redirect" method="get" action="aaa.php">
    name : <input type="text" name="value_1" id="value_1" value=""/><br>
    age: <input type="text" name="value_2" id="value_2" value=""/>
    <input type="submit" name="submit" value="send"/>
</form>

NB: name attribute in form tags is deprecated, use id attribute. Input , select and textarea tags should have id s as well.

JS:

$('.js-redirect').on('submit', function() {
    var newUrl = this.action.replace('.php', '/' + $('#value_1').val() + '/' + $('#value_2').val());
    this.action = newUrl;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM