html form submit calls a php but does not redirect

This question already has an answer here:

  • How to make a redirect in PHP? 27 answers

  • You can have your submit script check for a failure and redirect to the index.html for adding more on success.

    Bear in mind that you'll have to set the header before you output any other data with echo.

    header('refresh: 3; URL=index.html');

    Don't use mysql, use mysql i or PDO.

    Learn about SQL injection.

    So your sumbit.php might look like:

    <?php
    include 'config.php'; // store your configuration in a seperate file so 
                          // you only need to update it once when your environment changes
    
    $errors = false;
    $output = '';
    $nl = '<br>'.PHP_EOL;
    $redirect_url = 'index.html';
    
    $con = new mysqli(DBHOST,DBUSER,DBPASS,DBNAME);
    
    if ($con->connect_errno){
        $errors = true;
        $output .= "ERROR Can't connect to DB".$nl;
    };
    
    if (!$errors){
       //should validate/clean $_POST before using in query
       $name = $con->escape_string($_POST['name']);
       $city = $con->escape_string($_POST['city']);
       $email = $con->escape_string($_POST['email']);
       $mobile = $con->escape_string($_POST['mobile']);
       $sub = $con->escape_string($_POST['sub']);
       $slogan = $con->escape_string($_POST['slogan']);
    
       $sql="INSERT INTO members 
                (sName, sCity, sMobile, sEmail, sSub, sSlogan)
             VALUES ('$name', '$city', '$mobile', '$email',
                    '$sub','$slogan')";
    
       if (!$con->query($sql)){ //forgot a parenthesis here earlier
          $output .= 'ERROR: DB said: ('.$con->errno.') '.$con->error.$nl;
          $output .= 'Query was:'.$sql.$nl;
          $errors = true;
       }else{
         $output .= "1 record added".$nl;
       }
    }
    
    if (!$errors){
       //if there are no errors redirect to index.html;
       header('refresh: 2; URL='.$redirect_url);
       $output .= '...Redirecting...'.$nl;
    }else{
       //show the errors and allow display a link to go back/try again
       $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
    }
    echo $output;
    

    config.php would contain

    define('DBHOST','localhost');
    define('DBUSER','myuser');
    define('DBPASS','secretpass');
    define('DBNAME','mydb');
    

    EDIT / ADDITIONAL:

    If you want to do some validation, it is helpful to do some on the client so that your users won't have to submit and get rejected when you can already know that some inputs don't comply.

    But you will also need to validate on the server side (bad users can circumvent any client side validation you may have by editing the html in their browser)

    To help your users, you can use some of the new html5 input types available, optionally with some additional javascript:
    eg <input type="email" name="email">

    Your index.html can stay as a static page. It just presents the input form and maybe loads some javascript resources for validation.

    Your validation should happen in submit.php. If you're going to have more forms in your application you might consider having your server-side validation functions in a separate validations.php that you can include in your submit.php

    It could contain functions like:

    function validate_name($input){
        // fairly naive rule:
        // upper and lower case latin characters and space
        // at least three character long
        // you may want to look at allowing other characters such as é ö etc.
        $input = trim($input); //get rid of spaces at either end
        if (preg_match('/^[a-zA-Z ]{3,}$/',$input) == 1){
            return $input;
        }else{
            return false;
        }
    }
    

    In your submit.php you could then have

    ...
    include_once 'validations.php';
    ...
    
      if (!empty($_POST['name'])){
        if (!$name = $con->escape_string(validate_name($_POST['name'])){
            $errors = true;
            $output .= 'ERROR: Invalid Name: '.$_POST['name'].$nl;
        }
      }else{
        $errors = true;
        $output .= 'ERROR: No name specified'.$nl;
      }
    
      if (!empty($_POST['city']){
        ...
    
    ...
    

    To get the data already entered to populate in case of failure you can send the data back to the original via GET parameters.

    In submit.php, near the end you could add something like ...

    if (!$errors){
       //if there are no errors redirect to index.html;
       header('refresh: 2; URL='.$redirect_url);
       $output .= '...Redirecting...'.$nl;
    }else{
       //show the errors and allow display a link to go back/try again
       //add parameters to show the data already entered
       $redirect_url .= '?'.
            http_build_query(
                      array('name'=>$name,
                            'city'=>$city,
                            'mobile'=>$mobile,
                            ...
             ));
    
       $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
    }
    echo $output;
    

    and in index.php you'll have to read them in and set the values in your input fields if they exist.

    <?php 
    //we'll use urldecode() so that any special characters will be interpreted correctly
    if (!empty($_GET['name'])){
        $name = urldecode($_GET['name']);
    }else{
        $name = '';
    }
    if (!empty($_GET['city'])){
        $city = urldecode($_GET['city']);
    }else{
        $city = '';
    }
    ....
    ?>
    <input type="text" name="name" value="<?php echo $name; ?>"/>
    <input type="text" name="city" value="<?php echo $city; ?>"/>
    

    When you submit a form, the browser will jump the page which is specified in the target attribute of the form tag, in your case it's submit.php.

  • After processing the POST data, your submit page should render something, which redirects back to index.html, alternatives:

  • header http://php.net/manual/en/function.header.php
  • HTML "meta" tag https://en.wikipedia.org/wiki/Meta_refresh
  • If you don't want to reload the page, you should use AJAX to send data to the server:

  • you should set up a listener on the submit button,
  • send the data upon pressing it,
  • also you should disable default action (which is jumping to target page).
  • First you should try the first one, it's easier.


    index.html

    <form method="post" action="submit.php">
        //Html Codes
    </form>
    

    submit.php

    <?php
    $con = mysql_connect("localhost","myuser","mypassword");
    if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("mydb", $con);
    
    $sql="INSERT INTO members (sName, sCity, sMobile, sEmail, sSub, sSlogan)
    VALUES ('$_POST[name]', '$_POST[city]', '$_POST[mobile]', '$_POST[email]', '$_POST[sub]', '$_POST[slogan]')";
    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    else
    {
        header("location:index.html?Message=Success")
    }
    ?>
    
    链接地址: http://www.djcxy.com/p/34708.html

    上一篇: 如何重定向/调度在PHP?

    下一篇: HTML表单提交调用一个PHP,但不重定向