linanne Ответов: 0

Проверка на стороне сервера показывает встроенное сообщение об успехе или ошибке


I built a form for my class (private access only) where every one submit a form with some information. The information like Full name of the course, Subject, Select options for the list of teachers and a checkboxes for available class rooms. Some might like big or small rooms and available accessories for study. I did an effort for designing and built a form in bootstrap and php. Forms looks Okay and the validation is inline till I need to include one more feature in it. Every time when i submit a form it gets loaded. I mean, the form works with the php and html validation but the whole page gets loaded everytime i click the submit. I google it and know the this goal should be achieve by Ajax. I watched youtube videos and follow other questions here but got nothing. Inline validation or show the success message on the same page still not working. I want is when the user submit the form it will show the alert-success message on the samepage without refreshing or the error message inline if any errors there with server side validation. Codes easily available on internet.


Что я уже пробовал:

HTML:
<?php 
    include('ajaxreturn.php');
    ?>
    <!DOCTYPE html>
    <html lang="en">
      <head>

        <title>Hello, world!</title>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

      <body>


         <form id="submit" onsubmit="submitForm(); return false;">
              <div class="row">
         <div class="col-md-12">
              <div class="form-group">
              <label class="form-control-label" for="Name">Name</label>
              <input class="form-control" id="name" type="text" name="name" value= "<?php if (isset($_POST["name"])) echo htmlspecialchars($_POST["name"]) ?>">
              <span class="text-danger"><?php echo $name_error;?></span>
                  </div>
                  </div>
                  </div>

                  <div class="row">
                    <div class="col-md-12">
                  <div class="form-group">
              <label class="form-control-label" for="subject">Subject</label>
              <input class="form-control form-control" type="text" name="subject" id="subject" value= "<?php if (isset($_POST["subject"])) echo htmlspecialchars($_POST["subject"]) ?>">
              <span class="text-danger"><?php echo $subject_error;?></span>
                  </div>
                      </div>
                  </div>

                  <div class="row">
                  <div class="col-md-12">
                  <div class="form-group">
                  <label for="Category">Category</label>
                  <select class="form-control pt-0 pb-0" id="category">
                    <option>...</option>
                    ?>
                  </select>
                </div>
                </div>
          </div>
          <div class="row">
                <div class="form-check pl-3 pt-1">
                  <label class="form-check-label">
                    <input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
                    L-1
                  </label>
                </div>
                <span class="text-danger pl-3 pt-0"><?php echo $classroom_error;?></span>

                </div> 
                div class="row">
                <div class="form-check pl-3 pt-1">
                  <label class="form-check-label">
                    <input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
                    L-2
                  </label>
                </div>
                <span class="text-danger pl-3 pt-0"><?php echo $classrooms_error;?></span>

                </div> 
          <div class="row">
            <button id="submit" name="submit" value="submit" type="submit" class="btn btn-success">submit</button>
<span class="text-danger"> Wrong!</span>
<span class="text-success"> Thanks!</span>
          </div>
          </form>


        <!-- Optional JavaScript -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
        <!-- <script src="main.js"></script> -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

      </body>
    </html>


РНР:

<?php

// Form Variables 
$name = "";
$subject = "";
$category = "";
$classroom="";

//Error Variables
$name_error ="";
$subject_error = "";
$category_error = "";
$classroom_error = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $name_error = "Your Name";
  } else {
    $name = validation($_POST["name"]);
    // Function calling and checking the letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $name_error = "Your name must contain Letters, Numbers and Spaces"; 
    }
  }

  if (empty($_POST["subject"])) {
    $subject_error = "Your Subject";
  } else {
    $website = validation($_POST["subject"]);
    // Function calling and checking the letters and whitespace
    if ((!preg_match("/^[a-zA-Z ]*$]/", $subject)) {
      $subject_error = "Subjets must contain Letters, Numbers and Spaces";
    }
  }

  if (empty($_POST["category"])) {
    $category_error = "Please select categoy";
  } else {
    $category = validation($_POST["category"]);
  }

  if (empty($_POST["classroom"])) {
    $classroom_error = "Select the Class Room";
  } else {
    $classroom = validation($_POST["classroom"]);
  }
}




function validation($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

?>


Аякс:

<script>
  function _(id){ return document.getElementById(id); }
  function submitForm(){
  _("submit").disabled = true;
  _("status").innerHTML = 'please wait ...';
  var formdata = new FormData();
  formdata.append( "name", _("name").value );
  formdata.append( "subject", _("subject").value );
  formdata.append( "category", _("category").value );
  formdata.append( "classroom", _("classroom").value );
  var ajax = new XMLHttpRequest();
  ajax.open( "POST", "ajaxreturn.php" );
  ajax.onreadystatechange = function() {
    if(ajax.readyState == 4 && ajax.status == 200) {
      if(ajax.responseText == "success"){
        _("submit").innerHTML = '<h2>Thanks '+_("name").value+', your message has been sent.</h2>';
      } else {
        _("status").innerHTML = ajax.responseText;
        _("submit").disabled = false;
      }
    }
  }
  ajax.send( formdata );
}
</script>

0 Ответов