dqqyp90576
2014-09-17 08:26
浏览 35

使用PHP和Jquery Ajax进行输入验证

I want to validate an user input with ajax. It is the first time I use Ajax and I got stuck. If the input is correct I still get an error message and I don't know why.

I get as an error 'Subtax error in the jquery file'. What do I do wrong? Thank you in advance.

HTML:

<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                <div class="form-group">
                    <label for="inputName">Your name</label>
                    <input type="text" name="inputName" class="form-control" id="inputName"   placeholder="Name">
                </div>

                <div class="form-group">
                    <label for="inputEmail">Your e-mail</label>
                    <input type="text" name="inputEmail" class="form-control" id="inputEmail"    placeholder="E-mail">
                </div>                    

                <div class="form-group">
                    <label for="inputMess">Your message for us</label>
                    <textarea name="inputMess" class="form-control" id="inputMess"></textarea>
                </div>

                <button type="submit" name="send" class="btn btn-default">Send</button>
              </form>

              <div id='mess'></div>

PHP:

 <?php 

  sleep(1);

  $mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';

$return = array();
$mesaj = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {


    if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {

      $mesaj = "Please enter your name!";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) {

      $mesaj = "Please enter your e-mail!";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } elseif (empty($_POST['inputMess'])) {

      $mesaj = "Please tell us something";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } else {

      $return['error'] = false;
      $return['msg'] = 'Thank you for getting in touch. We will contact you!';
      echo json_encode($return);
       exit();

    }
  }


 ?> 

JavaScript:

$(document).ready(function() {

 var email_reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;   

$('form').submit(function(event) {

  event.preventDefault();

  if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) {

    alert('Please enter your name');

  } else if (!email_reg.test($('#inputEmail').val())) {

    alert('Please enter a valid e-mail adress');

  } else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) {

    alert('Please tell us something');

  } else {

    var formData = $('form').serialize();
    submitForm(formData);

  }

})


function submitForm(formData) {

    $.ajax({

        type: 'POST',
        url: $('form').action,
        data: formData,
        dataType: 'json',
        cache: false,
        timeout: 7000,
        success: function(data) {


                $('#mess').text(data.msg);

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {


                $('#mess').text('A communication error occured');

        },
        complete: function(XMLHttpRequest, status) {

            //$('form')[0].reset();

        }

    })
}


  })
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drqyxkzbs21968684 2014-09-17 08:37
    已采纳

    There might be some problem with your jquery file inclusion. Your code is working absolutely fine with me. I tried your code by saving it in a new php file as follows.

    <?php 
    
      sleep(1);
    
      $mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';
    
    $return = array();
    $mesaj = '';
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    
        if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {
    
          $mesaj = "Please enter your name!";
          $return['error'] = true;
          $return['msg'] = 'oops'.$mesaj;
          echo json_encode($return);
          exit();
    
        } elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) {
    
          $mesaj = "Please enter your e-mail!";
          $return['error'] = true;
          $return['msg'] = 'oops'.$mesaj;
          echo json_encode($return);
          exit();
    
        } elseif (empty($_POST['inputMess'])) {
    
          $mesaj = "Please tell us something";
          $return['error'] = true;
          $return['msg'] = 'oops'.$mesaj;
          echo json_encode($return);
          exit();
    
        } else {
    
          $return['error'] = false;
          $return['msg'] = 'Thank you for getting in touch. We will contact you!';
          echo json_encode($return);
           exit();
    
        }
      }
    
    
     ?> 
    <html>
    <head>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
    <body>
    <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                    <div class="form-group">
                        <label for="inputName">Your name</label>
                        <input type="text" name="inputName" class="form-control" id="inputName"   placeholder="Name">
                    </div>
    
                    <div class="form-group">
                        <label for="inputEmail">Your e-mail</label>
                        <input type="text" name="inputEmail" class="form-control" id="inputEmail"    placeholder="E-mail">
                    </div>                    
    
                    <div class="form-group">
                        <label for="inputMess">Your message for us</label>
                        <textarea name="inputMess" class="form-control" id="inputMess"></textarea>
                    </div>
    
                    <button type="submit" name="send" class="btn btn-default">Send</button>
                  </form>
    
                  <div id='mess'></div>
                  <script>
                  $(document).ready(function() {
                  var email_reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;   
    
    $('form').submit(function(event) {
    
      event.preventDefault();
    
      if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) {
    
        alert('Please enter your name');
    
      } else if (!email_reg.test($('#inputEmail').val())) {
    
        alert('Please enter a valid e-mail adress');
    
      } else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) {
    
        alert('Please tell us something');
    
      } else {
    
        var formData = $('form').serialize();
        submitForm(formData);
    
      }
    
    })
    
    
    function submitForm(formData) {
    
        $.ajax({
    
            type: 'POST',
            url: $('form').action,
            data: formData,
            dataType: 'json',
            cache: false,
            timeout: 7000,
            success: function(data) {
    
    
                    $('#mess').text(data.msg);
    
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
    
    
                    $('#mess').text('A communication error occured');
    
            },
            complete: function(XMLHttpRequest, status) {
    
                //$('form')[0].reset();
    
            }
    
        })
    }
    
    
      })
                  </script>
                  </body>
                  </html>
    

    Output:

    enter image description here

    打赏 评论
  • doujing5150 2014-09-17 08:35

    Try add header('Content-Type: application/x-javascript'); in php before outputing the json string.

    打赏 评论

相关推荐 更多相似问题