douzhang5199 2015-05-15 18:40
浏览 31

表格不应重新加载

I built a Feedback form with PHP. There is a Popup from Foundation 5 included.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <style type="text/css">
    .auto-style1 {
      margin-left: 1px;
    }
    .auto-style2 {
      margin-left: 0px;
    }
    .auto-style3 {
      text-align: center;
    }
  .auto-style4 {
      text-align: center;
      font-size: x-large;
  }
  .auto-style5 {
      color: #FF0000;
  }
  .auto-style6 {
      color: #000000;
  }
  .auto-style7 {
      text-align: left;
  }
  </style>
    <title>Rating</title>
                <!-- Sterne Scripts -->
    <script src='jquery.js' type="text/javascript"></script>
    <script src='jquery.MetaData.js' type="text/javascript" language="javascript"></script>
    <script src='jquery.rating.js' type="text/javascript" language="javascript"></script>
            <!-- Popup Scripts -->
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/foundation.css">

  <!-- If you are using the gem version, you need this only -->
  <link rel="stylesheet" href="css/app.css">

  <script src="js/vendor/modernizr.js"></script>

     <link rel="stylesheet" href="css/app.css">

  <script src="js/vendor/modernizr.js"></script>
    <link href='jquery.rating.css' type="text/css" rel="stylesheet"/>
 </head>
<body style="background-image: url('img/body-bg.jpg')">
  <?php
  $send = false;
  $error = $text = '';
  if ($_SERVER['REQUEST_METHOD'] === "POST") {
    $to       = 'kontakt@schoenholz.eu';
    $subject  = "Feedback vom ".date("d.m.Y");
    $antispam = $_POST['access'];

    $name     = $_POST['star1'];
    $select   = $_POST['Select'];
    $text     = $_POST['TextArea1'];
    $message  = "Bewertung:  ".$name. "
" . "Warum die Bewertung?:  " .$text . "
" . "Woher kennen Sie uns?: " .$select;

    $success = true;
    if ($antispam != 'irregeheim') {
      $success = false;    //Fehlerflag setzen
      $error  .= 'Kein Spam erwünscht!<br>'; // Fehlertext
    }

   if ($name == '') {
    $success = false;
    $error  .= '"<em>Wie bewerten Sie uns</em>" wurde nicht ausgefüllt';
  }

    if ($select == "- Bitte auswählen -") {
      $success = false;    //Fehlerflag setzen
      $error  .= '<br>"<em>Wie haben Sie uns gefunden</em>" wurde nicht ausgefüllt</br>'; // Fehlertext
    }


    // ist alles ok ? dann senden
    if($success === true) {
      if (@mail($to,$subject,$message)) {
        $send = true;
        echo 'Danke für Ihr Feedback!';
      } else {
        $error .= 'Ihr Feedback konnte leider nicht gesendet werden. Bitte versuchen sie es später erneut';
      }
    }
  }
  if ($send === false) {
  ?>
     <a href="#" height="87" data-reveal-id="firstModal" class="small round button" width="26">Feedback</a><br/> 

<div id="firstModal" class="reveal-modal small" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog">
        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
      <p class="auto-style4" style="width: 477px"><strong>Feedback&nbsp;</strong></p>
      <p class="auto-style7" style="width: 477px">Bitte füllen Sie alle mit
      <span class="auto-style6">*</span> gekennzeichneten Felder aus</p>
      <label id="Label1"></label>
      <fieldset style="width: 476px"><legend>Wie bewerten Sie uns? 
      <span class="auto-style5">*</span></legend>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Sehr schlecht") echo "checked";?> value="Sehr schlecht"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Schlecht") echo "checked";?> value="Schlecht"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Durchschnittlich") echo "checked";?> value="Durchschnittlich"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Gut") echo "checked";?> value="Gut"/>
<input name="star1" type="radio" class="star" <?php if (isset($name) && $name=="Hervorragend") echo "checked";?> value="Hervorragend"/>      </fieldset>
      <p style="height: 36px">&nbsp;Grund Ihrer Bewertung?</p>
          <textarea class="auto-style1" name="TextArea1" style="width: 505px; height: 105px"><?php echo htmlspecialchars($text, ENT_QUOTES);?></textarea>
      <p>Wie haben Sie uns gefunden? <span class="auto-style5">*</span></p>
      <p>
        <select name="Select" style="width: 151px">
          <option <?php if($select== "- Bitte auswählen -") echo "selected"; ?>>- Bitte auswählen -</option>
          <option <?php if($select== "Familie/Freunde") echo "selected"; ?>>Familie/Freunde</option>
          <option <?php if($select== "Suchmaschinen (Google etc.)") echo "selected"; ?>>Suchmaschinen (Google etc.)</option>
          <option <?php if($select== "Zeitungen") echo "selected"; ?>>Zeitungen</option>
          <option <?php if($select== "Örtliche") echo "selected"; ?>>Örtliche</option>
          <option <?php if($select== "Werbung") echo "selected"; ?>>Werbung</option>
          <option <?php if($select== "Sonstiges") echo "selected"; ?>>Sonstiges</option>
        </select>
      </p>
      <input type="hidden" name="access" value="irregeheim">
      <p class="auto-style3" style="width: 498px">
        <input class="auto-style2" name="Submit1" type="submit" value="Senden"></p>
    </form>
              <?php
  }

  if (!empty($error)) {
    echo $error;
  }
  ?>

   <a class="close-reveal-modal" aria-label="Close">&#215;</a>
</div>
  <script src="js/vendor/jquery.js"></script>
  <script src="js/foundation.min.js"></script>
  <script>
    $(document).foundation();
  </script>
</body>
</html>

The problem is that if I push the Feedback button and miss a field, the page reloads and I have to push the Feedback Button again. I already figured out that I have to use ajax and Javascript to handle this but I dont know how I should rewrite my script so it works. Can somebody help me with that?

  • 写回答

1条回答 默认 最新

  • douhe5092 2015-05-18 11:40
    关注

    I use this approach: 1) Create the form on html and put an id on each input element, then I put a span or something to display error message, like this:

    <input type="text" name="email" id="email">
    <span id="email-message" class="hidden"></span>
    

    2) On your php script, you need to create an array, validate each input and send json data. My array looks like this:

    $data = array(
        'message' => null,
        'form' => array(
            'has_errors' => false, // put true if there are input errors
            'email' => array(
                error => false,
                message => null
            );
        );
    );
    
    header("Content-Type: application/json");
    echo json_encode($data); 
    exit;
    

    on this way, you add inputs to $data['form'] as you need. $data['message'] it's a general error like 'Impossible to save now. Try again'.

    3) And finally, on your javascript file on success method (after json request to validate form), you check if "data.message" has a general error and if not you use a for each of the data.form to check each input and show the error message if it's necessary:

    $('#my-form').on("submit", function(event){
        event.preventDefault();
        var $form = $(this);
    
        $.ajax({
            url: $form.attr("action"),
            type: 'POST',
            data: $form.serialize(),
            dataType: 'json',
            cache: false
        }).done(function(data) {
            if(data.message) {
                // show general error
            } else if(data.form.has_errors){//Si hay errores de formulario
                //Recorremos todos los errores
                $.each(data.form, function(key, value){
                    if(value.error) {
                        $('#' + key + '-msg').html(value.message).removeClass('hidden');
                    } else {
                        $('#'+key+'-msg').html('').addClass('hidden');
                    }
                });         
            } else {
                // no errors on form so show info message or whatever you need
            }
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站