简体   繁体   中英

Onclick event not working with submit type button

I am new to PHP and HTML nad am working on a web page with a form and submit button, and i want to make submit button as a ref button too ie it will refer to some other page after submitting information to database. My problem is, with i connect the page with php and forward information with database, onclick event does nothing otherwise it works fine. I have tried

    onclick="location.href='https://www.google.com';">

and i even tired to make a function to refer to some link and called it in onclick event but of no use.

PS

Sorry if i have asked something funny.

You should use window.location

onclick="window.location='https://www.google.com'"

but instead of using the onclick attribute, you should attach the event directly to the element. If you use jquery, this could be

<button id="mybutton" />

and the script

$('#mybutton').on('click', function(e) {
    window.location = "http://www.google.com";
    e.preventDefault();
});

but in this case, your form isn't submitted. If you want to submit the form to the server, and then redirect, you should use

header('Location: http://www.google.com');

which is an http redirect, after your script is executed

Use something like this as Ram Sharma has suggested

 <form method="post" action="mypage.php">
        <input type="text" name="name" value="RN">
    <button type='submit' name="submit" value="Submit">submit</button>
</form>

then in mypage.php

    if($_POST['submit']){
       //save to database 
        header("Location: myotherpage.php");
       exit();
    }

There can be different ways

1) You can call some javaScript function to redirect the page

<script type = "text/javascript">
   function redirectUser(){
       window.location = "http://www.yoururl.com";

       window.navigate("http://www.yoururl.com"); //works only with IE
   }
</script>

<form>
    <button name="myBtn" value="Submit" onclick = "redirecrUser()">Submit</button>
</form>

2) You can create a link a bit styling it to look like button to redirect

<style>
    .linkToBtn{
        text-decoration: none;
        color: #ffffff;
        background-color: black;
        font-size: 20px;
        padding: 5px;
    }
</style>
<a href = 'yourUrl.com' class = 'linkToBtn'>Submit</a>

3) you can redirect it using the PHP

<form method = 'post' action = ''>
    <input type = 'submit' name = 'submitBtn' value = 'Redirect' />
</form>
<?php
    if(isset($_POST['submitBtn'])){
        header('Location: yourURL.com');
    }
?>

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