3

Input Validation with PHP and Jquery Ajax

 2 years ago
source link: https://www.codesd.com/item/input-validation-with-php-and-jquery-ajax.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Input Validation with PHP and Jquery Ajax

advertisements

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 

  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();

        }

    })
}

  })


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:

SkVZu.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK