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

时间:2014-09-17 08:26:08

标签: javascript php jquery ajax

我想用ajax验证用户输入。这是我第一次使用Ajax而且卡住了。如果输入正确,我仍会收到错误消息,但我不知道原因。

我在jquery文件中得到错误' Subtax错误'。我做错了什么? 提前谢谢。

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 个答案:

答案 0 :(得分:2)

您的jquery文件包含可能存在一些问题。你的代码对我来说非常好。我通过将其保存在新的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();

    }
  }


 ?> 
<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>

输出:

enter image description here

答案 1 :(得分:0)

在输出json字符串之前,尝试在php中添加header('Content-Type: application/x-javascript');